本文主要讲一下如何使用微信内置地图设置起点终点并导航
传送门:微信小程序API~位置信息
准备工作:在app.json文件中配置可获得当前位置的许可
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于小程序位置接口的效果展示"
}
},
第一步:获取起点的位置(设备所在的位置)
wx.getLocation({
//这里的type有两种类型,详情请点击最上方的传送门查看
type: 'gcj02',
success :(res)=> {
//获取当前经纬度
const latitude = res.latitude
const longitude = res.longitude
//获取当前速度
const speed = res.speed
//位置的精确度
const accuracy = res.accuracy
}
})
注意,在代码的编写过程中,一定要使用箭头函数
微信小程序的api中并没有使用箭头函数,但经过我的多次使用,发现使用箭头函数更加省心,不会因为某些特定原因使程序出错,所以之后的代码我都会使用箭头函数
第二步:在wx.getLocation的回调函数success中使用wx.openLocation
wx.getLocation({
type: 'gcj02',//参数类型,让获取的数据可以被getLocation函数使用
success :(res)=> {
//这里是起点信息
const latitude = res.latitude
const longitude = res.longitude
const speed = res.speed
const accuracy = res.verticalAccuracy
//这是从终点的经纬度,将他传给wx.openLocation的参数中
const endlat = Number(this.data.latitude)
const endlon = Number(this.data.longitude)
wx.openLocation({
//这里的两个参数决定了终点在哪
latitude: endlat,
longitude: endlon,
scale: 18
})
}
})
这里有个大坑,传参数的时候,一定要传Number类型的参数,不然会报错,这里是将终点的经纬度转成Number类型的方法
const endlat = Number(this.data.latitude)
const endlon = Number(this.data.longitude)