vue 使用高德地图JS API绘制车辆轨迹
高德开放平台官网:https://lbs.amap.com/api/javascript-api/guide/abc/prepare。
准备工作:
1、注册,拿到key。
2、在在 public/index.html 中加入:
<script type="text/javascript"> window._AMapSecurityConfig = { serviceHost:'您的代理服务器域名或地址/_AMapService', // 例如 :serviceHost:'http://1.1.1.1:80/_AMapService', } </script> <script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=您申请的key值"></script>
3、在webpack中注册全局变量:
在vue.config.js文件中添加
config.externals = { ‘AMap’: 'AMap' }
4、绘制地图
<div id="AMap"></div> //初始化地图 initMap(){ this.map = new AMap.Map("AMap"); } //初始化轨迹数据 initPath(){ //从接口获取到的数据进行处理 res.forEact(data=>{ this.path.push(new this.AMap.LngLat(data.lng,data.lat)) }) } //绘制地图轨迹 setMap() { //设置小车icon let car = new AMap.Icon({ image: require('../../common/images/car.png'),//自定义小车图形 size: new AMap.Size(25, 50),//图标大小 imageOffset: new AMap.Pixel(0, 20)//图标所用图片偏移量 }); //设置起始点定位icon this.localIcon = new AMap.Icon({ size: new AMap.Size(20, 50), image: require('../../common/images/maplocal.png'), }); //设置起点坐标 this.start_marker = new AMap.Marker({ position: new AMap.LngLat(this.path[0].lng, this.path[0].lat), icon: this.localIcon }); //设置终点坐标 this.end_marker = new AMap.Marker({ position: new AMap.LngLat(this.path[this.path.length - 1].lng, this.path[this.path.length - 1].lat), icon: this.localIcon }); //创建小车 this.car_marker = new AMap.Marker({ position: [this.path[0]],//小车开始时位置 icon: car, map: this.map }); // 创建折线实例 this.polyline = new AMap.Polyline({ path: this.path, borderWeight: 3, // 线条宽度,默认为 1 strokeColor: '#cc0033', // 线条颜色 lineJoin: 'round' // 折线拐点连接处样式 }); this.startAnimation(); this.map.add(this.start_marker);//添加起点坐标 this.map.add(this.end_marker);//添加终点坐标 this.map.add(this.polyline);//将线路添加至地图实例 this.map.setFitView([this.polyline]);//调整地图窗口至合适位置 }, startAnimation(){ this.car_marker.moveAlong(this.path,800);//开始动画(800为速度) }, pauseAnimation(){ this.car_marker.pauseMove();//暂停动画 }, resumeAnimation(){ this.car_marker.resumeMove();//继续动画 }, stopAnimation(){ this.car_marker.stopMove();//停止动画 }
react项目使用方式大同小异哦~
结束。