背景:uni-app 小程序 腾讯地图
我的需求就是,有起点和终点,以及一个规划路线的按钮
一开始,只有起点和终点,包含两个点的经纬度,那么视野区就要能够看见这两个点:
onReady() {
this.mapContext = uni.createMapContext("map", this) // 这个'map'名字要跟map组件的id要同名,才能拿到map组件,调用它的一些API
},
let points = [{
latitude: newVal[0].latitude,
longitude: newVal[0].longitude,
},
{
latitude: newVal[1].latitude,
longitude: newVal[1].longitude,
}
]
setTimeout(() => {
this.includePointsFn(points)
}, 1000)
// 缩放视野
includePointsFn(points) {
this.mapContext.includePoints({
padding: [80, 50, 80, 50],
points: points
})
},
根据自己的需求把这个代码放在所在地,我这是监听起点和终点数组变化,然后执行这个,只要终点和起点一变化,我就立马调用this.includePointsFn(points)
这个方法:
watch: {
markers: {
handler(newVal, oldVal) {
if (newVal.length !== 0) {
let points = [{
latitude: newVal[0].latitude,
longitude: newVal[0].longitude,
},
{
latitude: newVal[1].latitude,
longitude: newVal[1].longitude,
}
]
setTimeout(() => {
this.includePointsFn(points)
}, 1000)
}
},
deep: true,
}
}
一开始的准备做好了,那么点击规划路线按钮调下面这个方法,我用的是腾讯的sdk:
formSubmit() {
let _this = this;
let from = this.markers[0].latitude + ',' + this.markers[0].longitude
let to = this.markers[1].latitude + ',' + this.markers[1].longitude
this.qqmapsdk.direction({
mode: 'driving', // 可选值:'driving'(驾车)、'walking'(步行)、'bicycling'(骑行),不填默认:'driving',可不填
from,
to,
success: function(res) {
let ret = res
let coors = ret.result.routes[0].polyline
let pl = [];
let kr = 1000000
for (let i = 2; i < coors.length; i++) {
coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
}
//将解压后的坐标放入点串数组pl中
for (let i = 0; i < coors.length; i += 2) {
pl.push({
latitude: coors[i],
longitude: coors[i + 1]
})
}
// 设置polyline属性,将路线显示出来,将解压坐标第一个数据作为起点
_this.latitude = pl[0].latitude
_this.longitude = pl[0].longitude
_this.polyline = [{
arrowLine: true,
points: pl,
color: '#3ECA37',
width: 5
}]
setTimeout(() => {
_this.includePointsFn(pl) // 缩放视野展示所有经纬度
}, 1000)
},
fail: function(error) {
console.log(error)
},
complete: function(res) {
console.log(res)
}
})
}
这样视野就可以包含所有点了。。。
推一篇总结得很好得文章:https://blog.csdn.net/lyandgh/article/details/98348704?spm=1001.2101.3001.6650.2&utm_medium=distribute.pc_relevant.none-task-blog-2defaultCTRLISTdefault-2-98348704-blog-107694048.pc_relevant_aa&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2defaultCTRLISTdefault-2-98348704-blog-107694048.pc_relevant_aa&utm_relevant_index=5