在之前的vue-amap的使用中发现了一些不足的地方,就是不支持路线规划,因此另寻它法最终找到了高德地图sdk的方式(当然了如果能直接vue-amap实现功能的话还是觉得vue-amap比较方便)
index.html中引入高德地图sdk的cdn
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.14&key=3b576d3486dc84adc303919ebc399dba"></script>
vue组件中通过实例化AMap将地图画到id为container上,然后通过AMap.Driving设计路线,AMap.Marker画起始和终点坐标,AMap.Polyline画路线,map.setFitView设置最佳视角
<template>
<div class="about">
<div id="container"></div>
</div>
</template>
<script>
export default {
mounted () {
this.mapInit()
}
methods: {
mapInit() {
var that = this
var map = new AMap.Map('container');
map.plugin('AMap.Driving', function() {
var driving = new AMap.Driving({
policy: AMap.DrivingPolicy.LEAST_TIME
})
var startLngLat = [116.379028, 39.865042]
var endLngLat = [116.427281, 39.903719]
driving.search(startLngLat, endLngLat, function (status, result) {
if (status === 'complete') {
if (result.routes && result.routes.length) {
console.log(result.routes[0]);
var path = that.parseRouteToPath(result.routes[0])
var startMarker = new AMap.Marker({
position: path[0],
icon: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png',
map: map
})
var endMarker = new AMap.Marker({
position: path[path.length - 1],
icon: 'https://webapi.amap.com/theme/v1.3/markers/n/end.png',
map: map
})
var routeLine = new AMap.Polyline({
path: path,
isOutline: true,
outlineColor: '#ffeeee',
borderWeight: 2,
strokeWeight: 5,
strokeColor: '#0091ff',
lineJoin: 'round'
})
routeLine.setMap(map)
map.setFitView([ startMarker, endMarker, routeLine ])
console.log('绘制驾车路线完成')
}
} else {
console.log('获取驾车数据失败:' + result)
}
})
})
},
parseRouteToPath(route) {
var path = []
for (var i = 0, l = route.steps.length; i < l; i++) {
var step = route.steps[i]
for (var j = 0, n = step.path.length; j < n; j++) {
path.push(step.path[j])
}
}
return path
}
}
}
</script>
<style scoped lang="scss">
#container {width:600px; height: 400px; }
</style>