uniapp 编写H5 使用高德地图

2,129 阅读3分钟

uniapp的H5使用高德地图

目前高德地图提供的api 有HTML的 vue的 那么就可以直接用2个方式在H5中使用

h5高德地图.png

第一种直接用html,使用webview渲染

高德有现成的js api直接使用

uniapp中可以直接使用web-view打开本地html文件  如 新建了一个高德的html文件,业务是可以直接写在该html中的 \hybrid\html\map.html   详细见uniapp打开hybrid的html文件

其中html的例子代码如

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <title>轨迹回放</title>
    <link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css"/>
    <style>
        html, body, #container {
            height: 100%;
            width: 100%;
        }

        .input-card .btn{
            margin-right: 1.2rem;
            width: 9rem;
        }

        .input-card .btn:last-child{
            margin-right: 0;
        }
    </style>
</head>
<body>
<div id="container"></div>
<div class="input-card">
    <h4>轨迹回放控制</h4>
    <div class="input-item">
        <input type="button" class="btn" value="开始动画" id="start" onclick="startAnimation()"/>
        <input type="button" class="btn" value="暂停动画" id="pause" onclick="pauseAnimation()"/>
    </div>
    <div class="input-item">
        <input type="button" class="btn" value="继续动画" id="resume" onclick="resumeAnimation()"/>
        <input type="button" class="btn" value="停止动画" id="stop" onclick="stopAnimation()"/>
    </div>
</div>
<script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=你的高德key"></script>
<script>
    // JSAPI2.0 使用覆盖物动画必须先加载动画插件
    AMap.plugin('AMap.MoveAnimation', function(){
        var marker, lineArr = [[116.478935,39.997761],[116.478939,39.997825],[116.478912,39.998549],[116.478912,39.998549],[116.478998,39.998555],[116.478998,39.998555],[116.479282,39.99856],[116.479658,39.998528],[116.480151,39.998453],[116.480784,39.998302],[116.480784,39.998302],[116.481149,39.998184],[116.481573,39.997997],[116.481863,39.997846],[116.482072,39.997718],[116.482362,39.997718],[116.483633,39.998935],[116.48367,39.998968],[116.484648,39.999861]];

        var map = new AMap.Map("container", {
            resizeEnable: true,
            center: [116.397428, 39.90923],
            zoom: 17
        });

        marker = new AMap.Marker({
            map: map,
            position: [116.478935,39.997761],
            icon: "https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png",//
            offset: new AMap.Pixel(-13, -26),
        });

        // 绘制轨迹
        var polyline = new AMap.Polyline({
            map: map,
            path: lineArr,
            showDir:true,
            strokeColor: "#28F",  //线颜色
            // strokeOpacity: 1,     //线透明度
            strokeWeight: 6,      //线宽
            // strokeStyle: "solid"  //线样式
        });

        var passedPolyline = new AMap.Polyline({
            map: map,
            strokeColor: "#AF5",  //线颜色
            strokeWeight: 6,      //线宽
        });


        marker.on('moving', function (e) {
            passedPolyline.setPath(e.passedPath);
            map.setCenter(e.target.getPosition(),true)
        });

        map.setFitView();

        window.startAnimation = function startAnimation () {
            marker.moveAlong(lineArr, {
                // 每一段的时长
                duration: 500,//可根据实际采集时间间隔设置
                // JSAPI2.0 是否延道路自动设置角度在 moveAlong 里设置
                autoRotation: true,
            });
        };

        window.pauseAnimation = function () {
            marker.pauseMove();
        };

        window.resumeAnimation = function () {
            marker.resumeMove();
        };

        window.stopAnimation = function () {
            marker.stopMove();
        };
    });
</script>
</body>
</html>

第二种直接在vue中使用,引入高德js sdk

高德有现成的js api 也可以在vue中使用

  引入高德js  npm i @amap/amap-jsapi-loader --save 

其中vue的例子代码如

<!--H5 引入高德的包  npm i @amap/amap-jsapi-loader --save-->
<template>
	<div>

		<div id="container"></div>
		<div class="input-card">
			<h4>轨迹回放控制</h4>
			<div class="input-item">
				<button type="default" @click="startAnimation">开始动画</button>
				<button type="default" @click="pauseAnimation">暂停动画</button>
			</div>
			<div class="input-item">
				<button type="default" @click="resumeAnimation">继续动画</button>
				<button type="default" @click="stopAnimation">停止动画</button>
			</div>
		</div>
	</div>

</template>
<script>
	import AMapLoader from "@amap/amap-jsapi-loader";
	import {
		nextTick
	} from "vue";
	var lineArr = [
		[116.478935, 39.997761],
		[116.478939, 39.997825],
		[116.478912, 39.998549],
		[116.478912, 39.998549],
		[116.478998, 39.998555],
		[116.478998, 39.998555],
		[116.479282, 39.99856],
		[116.479658, 39.998528],
		[116.480151, 39.998453],
		[116.480784, 39.998302],
		[116.480784, 39.998302],
		[116.481149, 39.998184],
		[116.481573, 39.997997],
		[116.481863, 39.997846],
		[116.482072, 39.997718],
		[116.482362, 39.997718],
		[116.483633, 39.998935],
		[116.48367, 39.998968],
		[116.484648, 39.999861]
	];
	export default {
		name: "map-view",

		onLoad(options) {
			this.initAMap();
		},
		onUnload() {
			this.map?.destroy();
		},
		data() {
			return {
				map: false,
				marker: false
			}
		},
		mounted() {

		},
		unmounted() {

		},
		methods: {
			initAMap() {
				window._AMapSecurityConfig = {
					securityJsCode: "你注册的时候的key和securityJsCode",
				};
				AMapLoader.load({
						key: "你注册的时候的key和securityJsCode", // 申请好的Web端开发者Key,首次调用 load 时必填
						version: "2.0", // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
						plugins: ["AMap.Scale",
							"AMap.MoveAnimation"
						], //需要使用的的插件列表,如比例尺'AMap.Scale',支持添加多个如:['...','...']
					})
					.then((AMap) => {
						this.map = new AMap.Map("container", {
							// 设置地图容器id
							viewMode: "3D", // 是否为3D地图模式
							zoom: 11, // 初始化地图级别
							center: [116.397428, 39.90923], // 初始化地图中心点位置
						});
						this.initLineCar(this.map)
					})
					.catch((e) => {
						console.log(e);
					});
			},
			initLineCar(map) {
				//创建一条折线覆盖物
				var path = [
					new AMap.LngLat("116.368904", "39.913423"),
					new AMap.LngLat("116.382122", "39.901176"),
					new AMap.LngLat("116.387271", "39.912501"),
					new AMap.LngLat("116.398258", "39.904600"),
				];
				// 绘制轨迹
				var polyline = new AMap.Polyline({
					map: this.map,
					path: lineArr,
					showDir: true,
					strokeColor: "#28F", //线颜色
					// strokeOpacity: 1,     //线透明度
					strokeWeight: 6, //线宽
					// strokeStyle: "solid"  //线样式
				});
				// var polyline = new AMap.Polyline({
				// 	path: path,
				// 	borderWeight: 2, //线条宽度,默认为1
				// 	strokeColor: "red", //线条颜色
				// 	lineJoin: "round", //折线拐点连接处样式
				// });
				// map.add(polyline);
				//创建点标记
				// var marker1 = new AMap.Marker({
				// 	position: new AMap.LngLat(117.39, 39.9), //经纬度对象
				// });
				//map.add(marker1);
				var marker = new AMap.Marker({
					map: map,
					position: [116.478935, 39.997761],
					icon: "https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png",
					offset: new AMap.Pixel(-13, -26),
				});
				var passedPolyline = new AMap.Polyline({
					map: map,
					strokeColor: "#AF5", //线颜色
					strokeWeight: 6, //线宽
				});
				marker.on('moving', function(e) {
					passedPolyline.setPath(e.passedPath);
					map.setCenter(e.target.getPosition(), true)
				});
				//自动适配到合适视野范围
				//无参数,默认包括所有覆盖物的情况
				map.setFitView();
				//传入覆盖物数组,仅包括 polyline 和 marker1 在地图视野范围,marker2 不在地图视野范围
				//map.setFitView([polyline, marker1]); //简写
				//map.setFitView([polyline, marker1], false, [60, 60, 60, 60], 12); //完整写法
				this.marker = marker
				this.$nextTick(() => {
					this.startAnimation()
				})
			},
			startAnimation() {
				if (this.marker) {
					this.marker.moveAlong(lineArr, {
						// 每一段的时长
						duration: 500, //可根据实际采集时间间隔设置
						// JSAPI2.0 是否延道路自动设置角度在 moveAlong 里设置
						autoRotation: true,
					});
				}
			},
			pauseAnimation() {
				if (this.marker) {
					this.marker.pauseMove();
				}
			},
			resumeAnimation() {
				if (this.marker) {
					this.marker.resumeMove();
				}
			},
			stopAnimation() {
				if (this.marker) {
					this.marker.stopMove();
				}
			},
		},
	};
</script>
<style lang="scss" scoped>
	#container {
		width: 100%;
		height: 100vh;
	}

	.input-card {
		display: flex;
		position: fixed;
		bottom: 0;
		background-color: #fff;
		width: 100%;
		flex-direction: column;
		z-index: 999;

		.input-item {
			display: flex;
			width: 100%;
			flex-direction: row;
		}
	}
</style>

注意,提前申请高德的H5的key ,替换进代码,目前代码是完整的,2种方式均可以达到图片效果