1.引入配置 可参考官网
(开发环境用 在线地图)
<script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=申请的key值"></script>
2.初始化地图
this.map = new AMap.Map('mapIdForFence', {
resizeEnable: true,
center: window.SITE_CONFIG.centerGis,
zoom: 11
})
3.实现标绘功能
// 绘制多边形
drawPolygon () {
this.mouseTool && this.mouseTool.close()
AMap.plugin(['AMap.MouseTool'], () => {
this.mouseTool = new AMap.MouseTool(this.map)
switch (this.selectTool) {
case 'polygon': // 多边形
this.mouseTool.polygon({
strokeColor: '#238e0b',
fillColor: '#f5a444',
fillOpacity: 0.6,
selected: false // 判断当前选中状态
})
break
case 'rectangle': // 矩形
this.mouseTool.rectangle({
strokeColor: '#238e0b',
fillColor: '#f5a444',
fillOpacity: 0.6,
selected: false
})
break
case 'circle': // 圆形
this.mouseTool.circle({
strokeColor: '#238e0b',
fillColor: '#f5a444',
fillOpacity: 0.6,
selected: false
})
break
}
// 监听draw事件可获取画好的覆盖物
this.mouseTool.on('draw', (e) => {
let polygon = e.obj
this.polygonSelected(polygon)
this.polygonList.push(polygon)
console.log('绘制的多边形===========', this.polygonList)
})
})
},
// 监听点击选中绘制的图形 图形高亮
polygonSelected (polygon) {
polygon.on('click', (e) => {
console.log('选中==========', e)
polygon.selected = !polygon.selected
if (polygon.selected) {
this.selectedPolygon.push(polygon)
polygon.setOptions({
strokeColor: '#ef2c2c',
fillColor: '#ffb800'
})
} else {
this.selectedPolygon = this.selectedPolygon.filter(item => item._amap_id !== polygon._amap_id)
polygon.setOptions({
strokeColor: '#238e0b',
fillColor: '#f5a444'
})
}
console.log(this.selectedPolygon, this.selectedPolygon.length)
})
}
// 停止绘制
stopDraw () {
this.mouseTool.close()
this.selectTool = ''
},
// 结束绘制多边形 并保存
closeDrawPolygon () {
this.mouseTool.close()
this.selectTool = ''
this.savePolygon = []
for (let i = 0; i < this.polygonList.length; i++) {
let op = this.polygonList[i].getOptions()
let routePath = []
op.path && op.path.forEach(item => {
routePath.push([item.lng, item.lat])
})
let savearr = {
path: routePath,
center: op.center,
radius: op.radius,
zIndex: op.zIndex
}
this.savePolygon.push(savearr)
}
let save = JSON.stringify(this.savePolygon)
console.log('savePolygon=====', save)
// 可根据需要保存 到缓存或者数据库
this.saveSubmit(save)
},
// 移除选中 图形
delPolygon () {
this.map.remove(this.selectedPolygon)
this.selectedPolygon = []
},
// 清空 多边形
clearPolygon () {
this.map.remove(this.polygonList)
this.polygonList = []
},
如果需要重现之前保存过的图形,可调用
// 用保存的数据重新绘制多边形并添加事件
resetDraw (data) {
let savePolygon = JSON.parse(data)
for (let i = 0; i < savePolygon.length; i++) {
let polygon = (savePolygon[i].center && savePolygon[i].radius) ? new AMap.Circle(savePolygon[i]) : new AMap.Polygon(savePolygon[i])
polygon.setOptions({
strokeColor: '#238e0b',
fillColor: '#f5a444',
fillOpacity: 0.6,
selected: false
})
this.polygonList.push(polygon)
this.polygonSelected(polygon)
this.map.add(polygon)
}
},
其他
/* 去掉高德地图logo */
.amap-logo {
right: -100px !important;
left: auto !important;
display: none;
}
.amap-copyright {
right: -200px !important;
left: auto !important;
}