需求:根据markers来绘制标记点且进行连线,不同的路线绘制不同的颜色。
vue:
//html
<template>
<div class="map-container">
<div id="mapContainer"></div>
</div>
</tempalte>
//js
export default{
name:'map',
data(){
return{
map:{},
markerList:[],
driving:{}
}
},
mounted(){
this.mapInit();
},
methods:{
mapInit(){
this.map = new AMap.Map('mapContainer',{
zoom:13
})
this.addMarker();
let _this = this;
AMap.plugin('AMap.Driving',function(){
_this.driving = new AMap.Driving({
map:_this.map
})
})
},
addMarker(type='default',paramMarkers,initType){
let _this = this;
_this.map.clearMap();
let markers = [];
let bgColors = [];
if(type==='default'){
markers = this.initMarkers(initType);//初始化标记点经纬度
bgColors = ['#DC143C','#00af66'];
}else{
markers = paramMarkers;
bgColors = ['#00af66','00cae9',...];
}
markers.forEach(function(item,index){
item.forEach(function(itemMarker,indexMarker){
if(type==='default'){
const marker = new AMap.Marker({
map:_this.map,
position:[itemMarker.long,itemMarker.lat],
offset:new AMap.Pixel(-13,-36),
//设置文本内容
content:`<div class="marker-point" style="background-color:${bgColors[indexMarker]}"></div>`
})
_this.map.add(marker);
_this.markerList.push(marker);
}else{
const marker = new AMap.Marker({
map:_this.map,
position:[itemMarker.long,itemMarker.lat],
offset:new AMap.Pixel(-13,-36),
content:`<div class="marker-point" style="background-color:${bgColors[index]}"><span>
${indexMarker+1}</span></div>`
})
_this.map.add(marker);
_this.markerList.push(marker);
}
})
})
_this.map.setFitView([...this.markerList]);
//第一次进入这个页面不需要划线,只标记点即可。点击某个按钮时,触发划线动作及标点。
if(type !== 'default'){
_this.drivingRoute(markers,bgColors);
}
},
drivingRoute(marker,color){
let routeLineObj = {};
let startLngLat = [];
let endLngLat = [];
let _this = this;
//行驶路线规划
function parseRouteToPath(route){
let path = [];
//eslint-disable-next-line
for(let i=0,len=route.steps.length;i<len;i++){
let step = route.steps[i];
for(let j=0,lenj=step.path.length;j<lenj;j++){
path.push(step.path[j]);
}
}
return path;
}
function drawRoute(route,index){
const path = parseRouteToPath(route);
//生成 折线路线
routeLineObj = new AMap.Polyline({
zIndex:52,
path,
isOutline:true,
outlineColor:'#ffeeee',
borderWeight:2,
strokeWeight:5,
strokeColor:color[index]||'#A52A2A',
lineJoin:'round'
})
routeLineObj.setMap(_this.map)
}
//因为这里marker放的是二维数组,所以进行了两次循环
for(let i=0,len=marker.length;i<len;i++){
for(let j=0,lenj=marker[i].length;j<lenj;j++){
let markerItem = marker[i][j];
let markerItemEnd = {};
//这里进行了这个判断的目的,假设返回了7个点,希望按1->2->3->4->5->6->7的顺序连线
if(j !== marker[i].length-1){
markerItemEnd = marker[i][j+1];
startLngLat = [markerItem.long,markerItem.lat]
endLngLat = [markerItemEnd.long,markerItem.lat];
this.driving.search(startLngLat,endLngLat,function(status,result){
if(status === 'complete'){
if(result.routes && result.routes.length){
drawRoute(result.routes[0],i)
}
}
})
}
}
}
},
removeAllOverlay(){
this.map.clearMap();
this.markerList = [];
},
}
}
参考链接:https://blog.csdn.net/qq_29101609/article/details/106239155