map installation
npm install vue-amap --save
Set up Gaode map in the project
After the installation is successful, set the following content in main.js
import VueAMap from 'vue-amap'
Vue.use(VueAMap)
VueAMap.initAMapApiLoader({
key: '你的key',
plugin: ['AMap.MouseTool', 'AMap.PolyEditor', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PlaceSearch', 'AMap.Geolocation', 'AMap.Geocoder', 'AMap.DistrictSearch', 'AMap.InfoWindow'],
v: '1.4.4',
uiVersion: '1.0',
})
Introduce the installed Gaode components into the components:
<el-amap :amap-manager="amapManager" :events="events" :center="center" :zoom="zoom" :plugin="plugin" class="amap-demo" />
import {
AMapManager, lazyAMapApiLoaderInstance } from 'vue-amap'
const amapManager = new AMapManager() // 新建生成地图画布
export default {
data() {
const self = this
return {
car: require('@/assets/images/car1.png'), // 车辆图片
map: null,
amapManager,
marker: null,
events: {
init(o) {
lazyAMapApiLoaderInstance.load().then(() => {
self.initMap()
})
},
},
center: [121.472644, 31.231706],
zoom: 10,
plugin: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PolyEditor', 'AMap.CircleEditor', 'AMap.Geocoder', 'AMap.Geolocation', 'AMap.InfoWindow'],
}
},
methods: {
// 初始化地图
initMap() {
const map = amapManager.getMap()
this.map = map
},
initCar() {
// 构建车辆
const that = this
AMapUI.loadUI(['overlay/SimpleInfoWindow', 'overlay/SimpleMarker'], function (SimpleInfoWindow, SimpleMarker) {
for (let i = 0; i < that.vehicleInfoList.length; i++) {
const item = that.vehicleInfoList[i]
const marker = new SimpleMarker({
iconStyle: that.car,
// 显示定位点
// showPositionPoint:true,
map: that.map,
position: [item.longitude, item.latitude],
// Marker的label(见https://lbs.amap.com/api/javascript-api/reference/overlay/#Marker)
label: {
content: item.vehicleNo,
offset: new AMap.Pixel(0, 30),
},
})
const infoWindow = new SimpleInfoWindow({
// 模板, underscore
infoTitle: '',
infoBody: `<div class="vehicleCar">
<div>车型:${
item.vehicleTypeName}</div>
<div>司机:${
item.driverName}</div>
<div>联系方式:${
item.driverPhone}</div>
<div>已配数:${
item.assignedWaybillCount}</div>
<button class="mybtn">添加车辆</button>
</div>`,
// 基点指向marker的头部位置
offset: new AMap.Pixel(0, -31),
})
marker.on('click', function () {
that.openInfoWin(infoWindow, marker)
})
infoWindow.get$InfoBody().on('click', '.mybtn', function (event) {
// 阻止冒泡
event.stopPropagation()
that.addVehicleInfo(item)
})
}
})
}
},
openInfoWin(infoWindow, marker) {
infoWindow.open(this.map, marker.getPosition())
},
}