需求
获取出发点和目的地的距离、步行时间及路线规划
原理
- 采用微信小程序的map组件进行路线展示
- 腾讯地图的 微信小程序SDK 获取规划路线的坐标点
wxml
view class="container" map longitude="{{longitude}}" latitude="{{latitude}}" polyline='{{polyline}}' include-points='{{includePoints}}' markers='{{markers}}' scale="{{scale}}" show-location/map view class="tips"步行{{duration}}分钟(约{{distance}}米)/view view bindtap="chooseAddress"选择位置/view/viewjs
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');var qqmapsdk;Page({ data: { longitude:'', latitude:'', newCurrentLo :'', newCurrentLa :'', polyline:[], // 路线 includePoints:[], // 缩放视野以包含所有给定的坐标点 scale:16, markers:null, duration:null, distance:'' }, onLoad: function (options) { qqmapsdk = new QQMapWX({ key: 'UYFBZ-QFWHF-VVWJX-J7QP4-ZPPQ7-CZBJZ' }); const _self=this; // 获取当前位置 wx.getLocation({ type:'gcj02', success: function(res) { const { longitude, latitude}=res _self.setData({ longitude, latitude, markers: [{ id: 1, longitude: longitude, latitude: latitude, width: 32, height: 32, iconPath:'../images/start.png' }], includePoints:[{ longitude, latitude }] }) }, }) }, // 选择位置 chooseAddress(){ var _self=this; wx.chooseLocation({ success: res= { let markers=this.data.markers; if(markers.length1){ markers.pop() } markers.push({ id: 2, longitude: res.longitude, latitude: res.latitude, width: 32, height: 32, iconPath:'../images/end.png' }) var points = this.data.includePoints; if(points.length1){ points.pop() } points.push({ longitude: res.longitude, latitude: res.latitude }); this.setData({ newCurrentLo:res.longitude, newCurrentLa:res.latitude, includePoints: points, markers: markers, }) this.getPolyline() }, }) }, // 规划路线 getPolyline(){ const { latitude, longitude, newCurrentLo, newCurrentLa}=this.data; // 调用腾讯地图接口 qqmapsdk.direction({ mode: 'walking', from: { latitude, longitude }, to: { latitude: newCurrentLa, longitude: newCurrentLo }, success: res = { var coors = res.result.routes[0].polyline, pl = []; // 坐标解压(返回的点串坐标,通过前向差分进行压缩) var kr = 1000000; for (var i = 2; i coors.length; i++) { coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr; } // 将解压后的坐标放入点串数组pl中 for (var i = 0; i coors.length; i += 2) { pl.push({ latitude: coors[i], longitude: coors[i + 1] }) } this.setData({ longitude: pl[0].longitude, latitude: pl[0].latitude, polyline: [{ points: pl, color: '#00ff00', width: 4 }], duration: res.result.routes[0].duration, distance: res.result.routes[0].distance }) } }) }})













