现象
我们想用微信小程序实现在map>组件上自定义显示导航路径,但是目前为止官方并未给出相应的方法实现,map>组件确实有绘制点对点连线的属性polyline,但是呢我们没有一系列的坐标集合也是画不出一条路径的,
更糟糕的是即便你内置微信小程序Javascript SDK,它目前为止也不能给你相应的返回导航路径中所有坐标集合方法实现,不信你看介绍
解决方案
那我们只能用WebService API咯,
但是不要高兴的太早,根据文档,我们要的接口参数是酱紫的
那么我们开始写(下面是菜鸡版代码,非礼勿视)
wx.request()参数的data部分对”from”/”to”赋值不能采用惯用手法了,你会发现换了好几种方式依然不能如意,要么请求参数非法,要么语法编译又过不了,没办法,最后只能使用绝招了
哼哼,状态稳如老狗 @_@
ok,到此为止,我们已经拿到我们想要的坐标集合了,那么接下来就是提取坐标数组,然后给polyline绘制的问题了
利用polyline绘制路径
什么都不说了,直接上代码:
now_LocationTap: function () {
var that = this
wx.getLocation({
type: 'gcj02', // 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于 wx.openLocation 的坐标
success: function (res) {
console.log('当前位置数据Object如下:')
console.log(res)
that.setData({
now_Location: {
latitude: res.latitude,
longitude: res.longitude,
},
markers: [
{
iconPath: '/resources/wait/car.png',
width: 70,
height: 70,
latitude: res.latitude,
longitude: res.longitude
}
]
})
console.log('当前latitude:' + res.latitude)
console.log('当前longitude:' + res.longitude)
console.log('当前latitude同步结果:' + that.data.now_Location.latitude)
console.log('当前longitude同步结果:' + that.data.now_Location.longitude)
var now_Location = String(res.latitude + ',' + res.longitude)
var end_Location = String(that.data.endLocation.latitude + ',' + that.data.endLocation.longitude)
wx.request({
url: 'https://apis.map.qq.com/ws/direction/v1/driving/', //连接接口地址
data: {
from: now_Location,
to: end_Location,
policy: 'REAL_TRAFFIC', //结合路况的最优方式
key: '腾讯地图KEY',
},
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
console.log(res.data)
console.log('剩余距离:' + res.data.result.routes[0].distance + '米')
console.log('剩余时间:' + res.data.result.routes[0].duration + '分钟')
console.log('导航路线点串如下:')
console.log(res.data.result.routes[0].polyline)
var coors = res.data.result.routes[0].polyline
for (var i = 2; i < coors.length; i++)
{ coors[i] = coors[i - 2] + coors[i] / 1000000 }
console.log('路线坐标点串解压完毕!')
console.log('路线坐标点串解压结果如下:')
console.log(coors);
var coors_new=[] //记住微信小程序声明一个数组这样写
for(var j = 0; j < coors.length; j++){
coors_new.push({
latitude: parseFloat(coors[j]),
longitude: parseFloat(coors[j+1])
})
j++;
}
console.log('路线坐标点串格式化完毕!')
console.log('路线坐标点串格式化结果如下:')
console.log(coors)
console.log('已经产生新的经纬度数组coors_new如下:')
console.log(coors_new)
console.log('路线坐标点串解压后一共:' + coors.length + '个')
console.log('路线坐标点串转换后一共:' + coors_new.length + '个')
that.setData({
now_Duration: res.data.result.routes[0].duration, //剩余时间
now_Distance: res.data.result.routes[0].distance, //剩余距离
polyline_Object: [{
points: coors_new,//指定一系列坐标点,从数组第一项连线至最后一项
color: "#FF0000DD",
width: 2,
dottedLine: true
}],
})
console.log('更新points经纬度数组如下:')
console.log(that.data.polyline_Object[0].points)
console.log('更新polyline_Object如下:')
console.log(that.data.polyline_Object)
console.log('当前剩余时间 now_Duration同步结果:' + that.data.now_Duration+'分钟')
console.log('当前剩余距离now_Distance同步结果:' + that.data.now_Distance+'米')
}
})
},
})
}!
至此路径规划告一段落
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



