先上文档,说实话,找文档才是真麻烦
map | 微信开放文档 (qq.com)
微信小程序JavaScript SDK | 腾讯位置服务 (qq.com)
首先在wxml上写一个容器
<map
markers="{{markers}}" //标记的位置点
polyline="{{polyline}}" //路线显示
style="width: 100%; height: 100%;"
scale="{{scale}}" //缩放比
latitude="{{latitude}}" //纬度
longitude="{{longitude}}" //经度
></map>
然后定义一下配置需要的数据
Page({
data: {
latitude: 40.060539, //测试数据
longitude: 116.343847,
scale: 16,
markers: [{ //定位的点,会在地图上显示标记
latitude: 40.060539,
longitude: 116.343847,
},
{
latitude: 40.000539,
longitude: 116.303847,
iconPath: '/static/images/marker.png', //自定义标记图标
},
],
polyline: [], //路线显示对象
}
})
最后调一下API
//先把数据准备好
onLoad({
id
}) {
const flags = []
this.data.markers.forEach(item => {
flags.push({
latitude: item.latitude,
longitude: item.longitude
})
})
this.getPolyline(...flags)
}
//获取polyline对象
getPolyline(from, to) {
console.log(from, to);
QQMap.direction({
model: 'driving' //设置旅行方式,默认开车,具体可以看文档
from,
to,
success: (res) => {
console.log(res.result.routes[0].polyline);
const coors = res.result.routes[0].polyline
const points = []
//坐标解压(返回的点串坐标,通过前向差分进行压缩)
for (let i = 2; i < coors.length; i++) {
coors[i] = Number(coors[i - 2]) + Number(coors[i]) / 1000000
}
// 获取经纬度
for (let i = 0; i < coors.length; i += 2) {
points.push({
latitude: coors[i],
longitude: coors[i + 1]
})
}
// 渲染数据
this.setData({
latitude: points[30].latitude,
longitude: points[30].longitude,
polyline: [{
points,
color: '#5591af',
width: 4
}, ],
})
}
})
},