uniapp使用高德地图路径规划之map组件
1、项目前准备
1.1、首先你需要去申请一个属于自己的高德地图key,怎么申请暂不多说需要的去官网看
1.2、链接: 高德地图申请key直通车,点击前往。
有一个uniapp项目。
2、页面创建
新建一个uniapp的空白页 使用map组件渲染地图
<map id='map' :longitude="118.045616" :latitude="24.366646" :markers="covers"></map>
const covers = [{
latitude: 24.366646,
longitude: 118.045616,
width: 40,
height: 40,
callout: {
content: '点标记',
display:'ALWAYS'
},
iconPath: '../../../../static/addrs.png'
}]
就完成了 基础操作
3、路径规划
3.1、我们需要借助高德地图的路径规划查询获取到全部的路径规划 链接: 高德文档,点击前往。
const getDriving = () => {
let params =
`origin=118.045616,24.366646&destination=118.099481,24.583817&key=你的key`
uni.request({
url: `https://restapi.amap.com/v3/direction/driving?${params}`,
success: (res) => {
let data = res.data.route
if (data.paths && data.paths[0] && data.paths[0].steps) {
washData(data.paths[0].steps)
}
}
});
}
3.2、我们就获取到全部路径规划的数据,但是还是要洗一下数据。 ( ps:v3 和 v5返回的数据格式不一样)
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])
})
})
})
planList.value = [{
points: points,
width: 3,
arrowLine: true,
arrowIconPath: true,
color: '#204CF1',
}]
}
// template 里面的map组件使用
<map id='map' :longitude="118.045616" :latitude="24.366646" :markers="covers" :polyline="planList"></map>
3.2、然后就大功告成啦!! 其他的按照官网参数变成自己想要的样子就好了
4、最后 上代码~
<template>
<map id='map' :longitude="118.045616" :latitude="24.366646" :markers="covers" :polyline="planList"></map>
</template>
<script setup>
onLoad(() => {
getDriving()
})
const covers = [{
latitude: 24.366646,
longitude: 118.045616,
width: 40,
height: 40,
callout: {
content: '点标记',
display: 'ALWAYS'
},
iconPath: '../../../../static/addrs.png'
},{
latitude: 24.583817,
longitude: 118.099481,
width: 40,
height: 40,
callout: {
content: '点标记',
display: 'ALWAYS'
},
iconPath: '../../../../static/addrss.png'
}]
const getDriving = () => {
let params =
`origin=118.045616,24.366646&destination=118.099481,24.583817&key=你的key`
uni.request({
url: `https://restapi.amap.com/v3/direction/driving?${params}`,
success: (res) => {
let data = res.data.route
if (data.paths && data.paths[0] && data.paths[0].steps) {
washData(data.paths[0].steps)
}
}
});
}
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])
})
})
})
planList.value = [{
points: points,
width: 3,
arrowLine: true,
arrowIconPath: true,
color: '#204CF1',
}]
}
</script>
<style scoped>
#map {
width: 100%;
height: 100%;
}
</style>