介绍
uniapp通过高德地图接口实现路径规划,在地图上画出路线规划图.模拟导航位置.
一、获取高德地图的key.serverkey. 高德开放平台 | 高德地图API
二、引入map组件
<map ref="mapContext"
id="map"
:controls="mapInfo.controls"
style="width:100%; height:600rpx;"
:latitude="mapInfo.latitude"
:longitude="mapInfo.longitude"
:markers="mapInfo.markers"
:polyline="planList"
:enable-traffic="true"
:scale="17">
</map>
三、基础配置
const mapInfo = reactive({
latitude: 0,
longitude: 0,
endLatitude: 0,
endLongitude: 0,
controls: [],
config: {
width: 40,
height: 40,
callout: {
content: '当前位置',
display: 'ALWAYS'
},
iconPath: '/static/images/sign.png'
},
markers: []
})
四、获取当前位置
const getcurLocation = () => {
uni.getLocation({
type: 'gcj02',
isHighAccuracy: true,
success: res => {
// console.log(res)
mapInfo.latitude = res.latitude
mapInfo.longitude = res.longitude
if (mapInfo.markers[1]) {
mapInfo.markers[1].latitude = res.latitude
mapInfo.markers[1].longitude = res.longitude
} else {
mapInfo.markers.push({
markerId: 1,
latitude: res.latitude,
longitude: res.longitude,
width: 20,
height: 20,
callout: {
content: '当前位置',
borderRadius: 4,
borderWidth: 1,
borderColor: '#333300',
padding: '5',
// display: 'ALWAYS'
},
iconPath: '/static/images/hospital-1.png'
})
}
//规划路线
getDriving()
},
fail: () => {},
});
}
五、规划路线
const getDriving = () => {
// console.log(111, mapInfo.longitude, mapInfo.latitude)
uni.request({
url: 'https://restapi.amap.com/v3/direction/driving',
method: 'GET',
data: {
"origin": mapInfo.longitude + "," + mapInfo.latitude,
"destination": mapInfo.endLongitude + "," + mapInfo.endLatitude,
"key": '你的key'
},
success: res => {
// console.log(res)
let data = res.data.route
if (data.paths && data.paths[0] && data.paths[0].steps) {
washData(data.paths[0].steps)
}
},
fail: (err) => {
console.log(err)
}
});
}
let planList = ref([])
const washData = (steps) => {
let points = []
steps.forEach(item => {
const polen = item.polyline.split(';')
polen.forEach(vv => {
let splits = vv.split(',')
points.push({
longitude: parseFloat(splits[0]),
latitude: parseFloat(splits[1]),
// instruction: item.instruction
})
})
})
}
六、效果