前两天写了用腾讯位置服务计算2个地点间的距离 需要引入的可以看看前几天发的那篇用腾讯位置服务计算2个地点的距离 😃 看数据发现竟然有意料外的文章浏览 大意了 今天再加一篇 记录下怎么开发2个点之间的路线规划 然后在小程序里的地图上显示出来路线
引入各种的就不多赘述了 之前的文章里记录过 直接上代码和方法 路线规划的文档网址是这个
https://lbs.qq.com/miniProgram/jsSdk/jsSdkGuide/methodDirection
传入3个参数 "mode" "from" "to"
mode的参数有 ‘driving’(驾车)、‘walking’(步行)、‘bicycling’(骑行)、‘transit’(公交)做路线规划的时候 传入响应值就可以 如果没有变化 写成固定值也ok
from和to 传的是经纬度的数组 调用成功之后会返回相应数据 贴一下小程序里有map组件的代码 .js文件是这些
//路线规划 _makeOrderNavigatePlan: function (sendInfo, reciveInfo, exInfo) { var fromVal = sendInfo.latitude + ',' + sendInfo.longitude, toVal = reciveInfo.latitude + ',' + reciveInfo.longitude, that = this; //调用路线规划接口 qqmapsdk.direction({ //可选值:'driving'(驾车)、'walking'(步行)、'bicycling'(骑行),不填默认:'driving',可不填 mode: 'bicycling', from: fromVal, to: toVal, success: function (res) { var ret = res; var coors = ret.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] }) } that._setItemInMap(pl[0].latitude, pl[pl.length - 1].latitude, pl[0].longitude, pl[pl.length - 1].longitude, exInfo.latitude, exInfo.longitude); //设置polyline属性,将路线显示出来,将解压坐标第一个数据作为起点 that.setData({ latitude: pl[0].latitude, longitude: pl[0].longitude, polyline: [{ points: pl, color: '#1e1e1e', width: 4, }] }) }, fail: function (error) { console.error(error); }, complete: function (res) {} }); },
.wxml文件
<view class="order-map-v"> <map id="orderDetailMap" longitude="{{longitude}}" latitude="{{latitude}}" polyline="{{polyline}}" markers="{{markers}}" include-points="{{includePoints}}"> </map> </view>
单独写了一个地图元素设置方法 需要把腾讯位置服务方法调用后返回的数据设置到地图组件上
//设置界面元素 _setItemInMap: function (startLat, endLat, startLng, endLng, exLat, exLng) { var that = this, tempMarkers = [], mapCtx = that.data.mapObj; mapCtx.includePoints({ padding: [50, 50, 50, 50], points: [{ latitude: Number(exLat), longitude: Number(exLng) }, { latitude: startLat, longitude: startLng }, { latitude: endLat, longitude: endLng }] }) tempMarkers = [{ iconPath: Config.picPrefix + 'zzz.png', latitude: Number(exLat), longitude: Number(exLng), width: 30, height: 30 }, { iconPath: Config.picPrefix + '/xxx.png', latitude: startLat, longitude: startLng, width: 30, height: 30 }, { iconPath: Config.picPrefix + '/yyy.png', latitude: endLat, longitude: endLng, width: 30, height: 30 }] console.log('设置地图信息', tempMarkers); mapCtx.addMarkers({ markers: tempMarkers, clear: true, complete: function (res) { } }) },
tempMarkers数组里分别设置的是 配送车辆[配送员] 起点位置 终点位置 的图片url 经纬度 图片尺寸 传入之后setData 在map组件上就能显示出 2个位置的路线[程序会把路线画了加载好]和配送员的图片[按照业务也可以换成其他的] 效果是下面这样 传入的3个图片都可以自己设置 按照业务换成自己喜欢的就行

不过这是很早前写的方法了 用了几年 这段时间会拿出来看看有什么新的技术和方法可以引入更新下 到时候再来更新记录 今天就先这样
保持好奇 不断进步 下期见~