uniapp小程序使用高德地图api实现路线规划
路线规划
简介
路线规划常用于出行路线的提前预览,我们提供4种类型的路线规划,分别为:驾车、步行、公交和骑行,满足各种的出行场景。
高德开放平台
本例是驾车路线规划功能和位置选择地图api:chooseLocation
示例:
1、在页面的 js 文件中,实例化 AMapWX 对象,请求进行驾车路线规划。
首先,引入 amap-wx.js 文件(amap-wx.js 从相关下载页面下载的 zip 文件解压后得到)。
import amapFile from "@/libs/amap-wx.js";
然后在 onLoad 实例化 AMapWX 对象
onLoad() {
this.myAmapFunT = new amapFile.AMapWX({
key: 你申请的key
})
},
最后生成请求进行驾车路线规划数据
/**
*@author ZY
*@date 2023/1/9
*@Description:生成规划路线
*@param {string} start 开始位置
*@param {string} end 结束位置
*@param {number} strategy 10 默认多策略 策略 https://lbs.amap.com/api/webservice/guide/api/direction#driving
*
10,返回结果会躲避拥堵,路程较短,尽量缩短时间,与高德地图的默认策略也就是不进行任何勾选一致
* 4,躲避拥堵,但是可能会存在绕路的情况,耗时可能较长
2,距离优先,仅走距离最短的路线,但是可能存在穿越小路/小区的情况
*/
getPlanningRoute(start, end, strategy = 10) {
let that = this
uni.showLoading({
title: '加载中'
});
that.myAmapFunT.getDrivingRoute({
origin: start,
destination: end,
strategy: strategy, //备选方案
success: function(data) {
// console.log('所有路径',data)
if (data.paths && data.paths[0] && data.paths[0].steps) {
// 默认 10 会 对返回多条路径的方案 按照时间短的
let goodRouter = data.paths.sort((a, b) => {
return a.duration - b.duration
})[0]
that.distance = (goodRouter.distance * 0.001).toFixed(2) + '公里'
that.duration = '大约' + (goodRouter.duration / 60).toFixed(2) + '分钟'
let steps = goodRouter.steps
let points = []
for (var i = 0; i < steps.length; i++) {
var poLen = steps[i].polyline.split(';');
for (var j = 0; j < poLen.length; j++) {
points.push({
longitude: parseFloat(poLen[j].split(',')[0]),
latitude: parseFloat(poLen[j].split(',')[1])
})
}
}
that.polyline = [{
points: points,
color: strategy === 10 ? '#0ee532' : strategy === 2 ? '#0742d9' :
'#ee6b06',
width: 8,
}]
}
uni.hideLoading();
},
fail: function(info) { //失败回调
console.log('路线规划失败')
console.log(info)
uni.hideLoading();
uni.showToast({
title: '路线规划失败',
icon: 'error'
});
},
})
},
2.完整源码组件
{{item.name}}
距离:{{distance}} 时间:{{duration}}
您将在 {{startPoint.name | fmtEndAddr}} 上车
{{endPoint.name|fmtEndAddr}}
请选择目的地
发送给司机