1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > vue 集成封装 高德地图webJs 绘制线路规划自定义多条轨迹回放

vue 集成封装 高德地图webJs 绘制线路规划自定义多条轨迹回放

时间:2020-07-31 20:15:43

相关推荐

vue 集成封装 高德地图webJs  绘制线路规划自定义多条轨迹回放

开发需求

在地图上 绘制三条线路 其中两条 为 请求接口返回(项目自己的数据 北斗&app),另外一条调取高德的路线规划接口,将返回的数据进行处理,然后根据需求绘制三条折线 线路

实现效果

高德 开放平台 文档参考

路线规划:/api/javascript-api/guide/services/navigation

地图折线:/api/javascript-api/reference/overlay#polyline

轨迹回放:/demo/javascript-api/example/marker/replaying-historical-running-data/

===================================================================

1.高德地图的webjs 封装 异步调取

注意 动态生成 script 标签的src 时 后边加上 地图 所需要的一些基础插件

此处:Driving 线路规划 ToolBar 工具栏 OverView 鹰眼 MapType 图层

/*** @author deep1nBlur* @email* @create date -11-17 08:54:47* @modify date -03-27 13:07:29* @desc [高德地图封装 异步初始化]*/const mapKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // 高德应用key /dev/key/appexport default function mapLoader() {return new Promise((resolve, reject) => {if (window.AMap) {resolve(window.AMap);} else {var script = document.createElement("script");script.type = "text/javascript";script.async = true;script.src ="/maps?v=1.4.15&callback=initAMap&key=" +mapKey +"&plugin=AMap.Driving,AMap.ToolBar,AMap.OverView,AMap.MapType";script.onerror = reject;document.head.appendChild(script);}window.initAMap = () => {resolve(window.AMap);};});}

2.地图初始化

项目中 地图展示在弹框中 另需要请求两个接口 因数据量较大 请求时间 可能过长 而且还需要对请求回来的数据进行二次处理 (数据提取) 因此将地图初始化 展示出地图

-页面结构&基础数据

<template><div class="root-map-bar"><div id="map-container"></div><div class="legend"><div class="input-item" v-for="(v, i) in legend" :key="i"><template v-if="v.show"><inputtype="checkbox"name="mapStyle"value="road"checked@click="e => handleClick(e, i)"/><span class="input-text" :style="{ '--color': v.color }">{{v.name}}</span><div class="line" :style="{ '--color': v.color }"></div></template></div></div></div></template>data: () => ({map: "",legend: [{ name: "APP轨迹", color: "#28F", show: false, line: "" },{ name: "北斗轨迹", color: "#00e500", show: false, line: "" },{ name: "规划线路", color: "#ff3300", show: false, line: "" }]}),

-初始化方法 在mounted 钩子调用

initMap() {// /初始化地图const that = this;mapLoader().then(AMap => {that.map = new AMap.Map("map-container", {resizable: true,center: [116.397451, 39.909187],zoom: 11,mapStyle: "amap://styles/fresh",// features: ["road", "building", "bg"],layers: [// 路网new AMap.TileLayer.RoadNet()]});that.map.addControl(new AMap.OverView());that.map.addControl(new AMap.ToolBar());that.map.addControl(new AMap.MapType());this.drawTraceLine();// });},

-地图初始化后 调用drawTraceLine() 继续往下请求数据 绘制线路折线

$emit 告知外层组件展示loading效果

params 是父组件传递过来的一些基础数据 比如车牌号 始发地 目的地 等等

traceLineList 要存放三个线路折线数据的数组

appTraceLine app定位线路数据

beidouTraceLine 北斗定位线路数据

drivingOption 高德 传入起始点地址后返回的线路数据

三条线路的数据都需要进行处理 Polyline 的path 参数 =>折线的节点坐标数组 eg [[116.478935,39.997761],[116.478935,39.997761]]

三条线路 都有 不存在数据的情况 没有就传入一个空数组占位

markerList 地图线路标注 类似echarts的legend 用于生成起始点标注

colorList 不同线路轨迹的自定义颜色

后面有一段注释掉的代码段 想试验一下动态效果 线路标注经过后变色 但因数据坐标繁多 小车会在地图上转来转去 临时废弃 有空再研究

处理后的三条线路的数据 如下图

3.绘制线路

async drawTraceLine() {// 绘制地图轨迹const that = this;// 构造路线导航类// 根据起终点经纬度规划驾车导航路线that.$emit("update:modalLoading", true);let traceLineList = [];const appTraceLine = await getGps(that.params["code"]); // app 轨迹const temp = [];if (appTraceLine && appTraceLine.data) {// 处理 gps 字符串 => 数字JSON.parse(appTraceLine.data).forEach(item => {temp.push([Number(item["lon"]), Number(item["lat"])]);});}traceLineList.push(temp);const beidouParams = {carNum: that.params["cycph"],startTime: that.params["qsfwsj"],endTime: that.params["jsfwsj"]};const beidouTraceLine = await fromSinoiovTrack(beidouParams); //北斗轨迹const _temp = [];if (beidouTraceLine.data && beidouTraceLine.data.allTrack) {// 处理 北斗 轨迹数据beidouTraceLine.data.allTrack.forEach(item => {_temp.push([item["lnglat"][0], item["lnglat"][1]]);});}traceLineList.push(_temp);let drivingOption = {policy: AMap.DrivingPolicy.LEAST_TIME, // 其它policy参数请参考 /api/javascript-api/reference/route-search#m_DrivingPolicyferry: 1, //默认为0,表示可以使用轮渡,为1的时候表示不可以使用轮渡province: that.params["cycph"].substr(0, 1) // 车牌省份的汉字缩写 用于判断是否限行};const driving = new AMap.Driving(drivingOption);driving.search([{ keyword: that.params["sfdxxdz"], city: that.params["sfdmc"] },{ keyword: that.params["mddxxdz"], city: that.params["mddmc"] }],function(status, result) {// result 即是对应的驾车导航信息,相关数据结构文档请参考 /api/javascript-api/reference/route-search#m_DrivingResultconst temp = [];const _result = result.routes && result.routes[0]["steps"];_result &&_result.map(route => {route["path"].forEach(path => {temp.push([path.lng, path.lat]);});});traceLineList.push(temp);let markerList = []; // 起始点标注的坐标const filterList = traceLineList.filter(arr => {// 判断至少一项数组有值return arr.length > 0;});if (filterList.length) {markerList.push(filterList[0][0],filterList[0][filterList[0].length - 1]);// ==============↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓绘制 起始点 图标↓↓↓↓↓↓↓↓↓↓↓↓====================const startIcon = new AMap.Icon({// 图标尺寸size: new AMap.Size(25, 34),// 图标的取图地址image:"/jsapi_demos/static/demo-center/icons/dir-marker.png",// 图标所用图片大小imageSize: new AMap.Size(135, 40),// 图标取图偏移量imageOffset: new AMap.Pixel(-9, -3)});// 将 icon 传入 markerconst startMarker = new AMap.Marker({position: new AMap.LngLat(markerList[0][0], markerList[0][1]),icon: startIcon,offset: new AMap.Pixel(-13, -30)});// 创建一个 iconconst endIcon = new AMap.Icon({size: new AMap.Size(25, 34),image:"/jsapi_demos/static/demo-center/icons/dir-marker.png",imageSize: new AMap.Size(135, 40),imageOffset: new AMap.Pixel(-95, -3)});// 将 icon 传入 markerconst endMarker = new AMap.Marker({position: new AMap.LngLat(markerList[1][0], markerList[1][1]),icon: endIcon,offset: new AMap.Pixel(-13, -30)});// 将 markers 添加到地图that.map.add([startMarker, endMarker]);// =============↑↑↑↑↑↑↑↑↑↑↑↑↑绘制 起始点 图标↑↑↑↑↑↑↑↑↑↑↑↑========const colorList = ["#28F", "#00e500", "#ff3300"];// 绘制轨迹;if (traceLineList[0].length) {const polyline_GPS = new AMap.Polyline({// gps 折线map: that.map,path: traceLineList[0],showDir: true,strokeColor: colorList[0], //线颜色// strokeOpacity: 1,//线透明度strokeWeight: 6 //线宽// strokeStyle: "solid" //线样式});that.legend[0]["show"] = true;that.legend[0]["line"] = polyline_GPS;}if (traceLineList[1].length) {const polyline_BEIDOU = new AMap.Polyline({// 北斗折线map: that.map,path: traceLineList[1],showDir: true,strokeColor: colorList[1], //线颜色// strokeOpacity: 1,//线透明度strokeWeight: 6 //线宽// strokeStyle: "solid" //线样式});that.legend[1]["show"] = true;that.legend[1]["line"] = polyline_BEIDOU;}if (traceLineList[2].length) {const polyline_GAODE = new AMap.Polyline({// 高德规划折线map: that.map,path: traceLineList[2],showDir: true,strokeColor: colorList[2], //线颜色// strokeOpacity: 1,//线透明度strokeWeight: 6 //线宽// strokeStyle: "solid" //线样式});that.legend[2]["show"] = true;that.legend[2]["line"] = polyline_GAODE;// const passedGpsLine = new AMap.Polyline({// // gps 折线// map: that.map,// // path: traceLineList[2],// showDir: true,// strokeColor: colorList[2], //线颜色// // strokeOpacity: 1,//线透明度// strokeWeight: 6 //线宽// // strokeStyle: "solid" //线样式// });// const marker = new AMap.Marker({// map: that.map,// position: markerList[0],// icon: "/images/car.png",// offset: new AMap.Pixel(-26, -13),// autoRotation: true,// angle: -90// });// marker.on("moving", function(e) {// passedGpsLine.setPath(e.passedPath);// });// marker.moveAlong(traceLineList[2], 1000000);}that.map.setFitView();} else {that.$message({ message: "未查询到轨迹!", type: "error" });}that.$emit("update:modalLoading", false);});}

4.图例 legend 的 点击方法

handleClick(e, i) {// 图例 折线显示与隐藏if (e.target.checked) this.legend[i].line.show();else this.legend[i].line.hide();},

5.样式参考

.root-map-bar {height: 100%;display: flex;position: relative;#map-container {flex: 1;}.legend {min-width: 0;position: absolute;background-color: #fff;background-clip: border-box;bottom: 10px;right: 10px;border-radius: 0.4rem;box-shadow: 0 2px 6px 0 rgba(114, 124, 245, 0.5);padding: 5px 10px;.input-item {display: flex;align-items: center;height: 30px;.input-text {color: var(--color);margin-left: 5px;}.line {margin-left: 5px;width: 35px;height: 5px;background-color: var(--color);}}}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。