百度地图绘制途径点
百度地图Api地址:
https://lbsyun.baidu.com/
公司项目中要求绘制物流信息,需体现途径点
但是我在其中没有找到有关绘制路线,设定途径点的相关说明
其实就是下面这句,给 search方法的第三个参数传一个waypoints对象:
其中middlePoints为标点的数组
//途经点方式化路线:
driving.search(startPoint, endPoint, { waypoints: middlePoints })
但是这个方法并不精准,由于没找到相关官方说明,也没深入考究,效果如下:
计算路线并未完全经过途径点
于是我们换一种思路
分段绘制路线
多次执行 driving.search(startPoint, endPoint)
for (let i = 0; i < middlePoints.length; i++) {
if (i === 0) {
driving.search(startPoint, middlePoints[i])
} else {
driving.search(middlePoints[i - 1], middlePoints[i])
}
}
driving.search(middlePoints[middlePoints.length - 1], endPoint)
但是这时就需要运用到更底层一点的函数
链接: 百度地图jsapi 类参考
在路线的构造函数里面,绘制途径点的每一段路线,并修改样式等等
最终详细代码如下:
//点的坐标值
var gps = [
{lng: 125.532203,lat: 43.715047},
{lng: 123.545295,lat: 42.009887},
{lng: 116.186376,lat: 39.974898},
{lng: 114.539818,lat: 38.040826},
{lng: 113.675145,lat: 34.815406},
{lng: 112.95765,lat: 28.234227,},
{lng: 109.940493,lat: 27.62963,},
{lng: 106.684172,lat: 26.5924,},
{lng: 102.74715,lat: 24.926418,}
]
// 实例化地图
var map = new BMapGL.Map('container')//注意这里的container为元素id,且不能修改
map.centerAndZoom(new BMapGL.Point(116.404, 39.915), 11)
map.enableScrollWheelZoom(true)//地图和滚轮放大
//建立初始点,结束点,途经点数组
var middlePoints = []
var startPoint = new BMapGL.Point(gps[0].lng, gps[0].lat)
var endPoint = new BMapGL.Point(
gps[gps.length - 1].lng,
gps[gps.length - 1].lat
)
for (let i = 0; i < gps.length; i++) {
if (i === 0 || i === gps.length - 1) {
continue
}
var point = new BMapGL.Point(gps[i].lng, gps[i].lat)
middlePoints.push(point)
}
//调整到最佳视野
setTimeout(function () {
map.setViewport([startPoint, endPoint])
}, 1000)
//创建百度地图驾车实例
var driving = new BMapGL.DrivingRoute(map, {
renderOptions: { map: map, autoViewport: false },
onSearchComplete(results) {
// 绘制途径路线
var pts = results.getPlan(0).getRoute(0).getPath()
var polyline = new BMapGL.Polyline(pts)
polyline.setStrokeColor('#001E50')
polyline.setStrokeOpacity(1)
map.addOverlay(polyline)
},
onMarkersSet(routes) {
// 删点画点
map.removeOverlay(routes[0].marker)
map.removeOverlay(routes[routes.length - 1].marker)
middlePoints.forEach((element) => {
var marker = new BMapGL.Marker(element)
map.addOverlay(marker)
})
var startMarker = new BMapGL.Marker(startPoint)
var endMarker = new BMapGL.Marker(endPoint)
map.addOverlay(startMarker)
map.addOverlay(endMarker)
},
onPolylinesSet(routes) {
// 路线绘制
routes.forEach((Route) => {
var polyline = Route.getPolyline()
polyline.setStrokeColor('#001E50')
// polyline.setStrokeOpacity(1)
polyline.setStrokeWeight(1)
})
},
})
//途经点方式化路线:
// driving.search(startPoint, endPoint, { waypoints: middlePoints })
//分段画路线:
for (let i = 0; i < middlePoints.length; i++) {
if (i === 0) {
driving.search(startPoint, middlePoints[i])
} else {
driving.search(middlePoints[i - 1], middlePoints[i])
}
}
driving.search(middlePoints[middlePoints.length - 1], endPoint)
建议根据需求研究一下api, 继续优化样式等
最终效果:
欢迎交流提问 ~