效果:
上代码:
<template>
<section>
<div id="leafletMap" class="home" :style="{height: '92vh',width: '100vw' ,background:'#000'}"></div>
</section>
</template>
<script>
import L from 'leaflet'
require('../../../util/leaflet.contextmenu.js')
require('../../../util/leaflet-ant-path.js')
import startIcon from '@assets/img/start.png'
import guoIcon from '@assets/img/guo.png'
import stopIcon from '@assets/img/stop.png'
methods:{
initMap() {
let map = L.map('leafletMap', {
minZoom: 6,
maxZoom: 14,
center: [22.50, 113.31], //广东的中心
zoom:10,
zoomControl: false,
attributionControl: false,
crs: L.CRS.Baidu,
contextmenu: true,
contextmenuWidth: 140,
contextmenuItems: [{
text: '设置为起点',
callback: that.setStartPoint,
},
{
text: '设置为中间点',
callback: this.setWaypoints,
},
{
text: '设置为终点',
callback: that.setStopPoint,
},
'-',
{
text: '开始规划',
callback: that.calcRoute,
},
],
})
},
setStartPoint(e) {
this.startPoint = [e.latlng.lat, e.latlng.lng]
L.marker([e.latlng.lat, e.latlng.lng], {
icon: L.icon({
iconUrl: startIcon,
iconSize: L.point(20, 30),
}),
}).addTo(this.map)
},
setWaypoints(e) {
this.wayPoint = [e.latlng.lat, e.latlng.lng]
L.marker([e.latlng.lat, e.latlng.lng], {
icon: L.icon({
iconUrl: guoIcon,
iconSize: L.point(20, 30),
}),
}).addTo(this.map)
},
setStopPoint(e) {
this.endPoint = [e.latlng.lat, e.latlng.lng]
L.marker([e.latlng.lat, e.latlng.lng], {
icon: L.icon({
iconUrl: stopIcon,
iconSize: L.point(20, 30),
}),
}).addTo(this.map)
},
calcRoute() {
let that=this
let url = '/common/route'
let grahhVo = {
fromLat: this.startPoint[0],
fromLng: this.startPoint[1],
toLat: this.endPoint[0],
toLng: this.endPoint[1],
vehicle: '',
}
postAction(url, grahhVo).then(res => {
console.log(res)
that.success(res)
})
},
success(res) {
var coords=res.result.point
// var coords = [
// [25.376636777267127, 114.91269229996807],
// [25.066564774717097,113.7775998641828],
// [24.066564774717097,115.7775998641828]
// ]
var path = L.polyline.antPath(coords, {
"paused": true, //暂停 初始化状态
"reverse": false, //方向反转
"delay": 2000, //延迟,数值越大效果越缓慢
"dashArray": [10, 20], //间隔样式
"weight": 5, //线宽
"opacity": 0.9, //透明度
"color": "pink", //颜色
"pulseColor": "pink" //块颜色
});
path.addTo(this.map);
var mark=[res.result.point[0]]
let distance = (res.result.distance/1000).toFixed(2)
let time = (res.result.time/1000/3600).toFixed(2)
for (var a = L.featureGroup().addTo(this.map), t = 0; t < mark.length; t++) {
var n = mark[t];
var divIcon;
divIcon = L.divIcon({
iconSize: [0, 0],
popupAnchor: [0, 0],
html: '<div style="width:150px;height:50px;background:#fff;border-radius:5px;padding:5px;color:#000;margin-left:30px;margin-top:30px;" id="wayTip">全程'+distance+'公里,开车预计'+time+'小时</div>'
});
var o = L.marker(n, {
icon: divIcon
});
a.addLayer(o);
}
},
}