实现地图框形选点、圆形选点、多边形选点,并修改选中点的颜色,主要使用BMap Draw
效果图:
1、引入百度地图js,引入的百度api所用的key请去其官网申请并替换使用:
<script type="text/javascript" src="https://api.map.baidu.com/api?v=1.0&&type=webgl&ak=你申请的key"></script>
2、安装bmap-draw
npm install bmap-draw
3、按需引入相关插件
import { DrawScene, Select, DrawingType, OperateEventType, GeoCalculator } from 'bmap-draw'
4、初始化地图:
initMap() {
const map = new BMapGL.Map(this.$refs.map)
map.enableScrollWheelZoom(true)
this.map = map
window.map = map
const myCity = new BMapGL.LocalCity() // 定位当前城市
myCity.get(result =>{
console.log(result)
const cityName = result.name
const point = new BMapGL.Point(result.center.lng, result.center.lat)
this.map.centerAndZoom(point, 8)
this.map.setCenter(cityName)
this.initDraw()
this.addTestData()
})
}
5、初始化绘制工具
initDraw() {
const scene = new DrawScene(this.map)
// 存储选择的元素
this.selectedOverlay = []
const polyLayer = new BMapGL.GeoJSONLayer('poly',{
markerStyle: function(properties){ // 默认样式
return {
icon: new BMapGL.Icon(
require('./img/markers_red.png'),
new BMapGL.Size(21, 25),
{
anchor: new BMapGL.Size(10, 25)
}
)
}
}
})
this.map.addGeoJSONLayer(polyLayer)
const point = new BMapGL.Point(113.27143134, 23.13533631)
const marker = new BMapGL.Marker(point) // 创建标注
polyLayer.addOverlay(marker.toGeoJSON())
polyLayer.addEventListener('click', (e) =>{
console.log(polyLayer.pickOverlays(e)) // 判断是否点击覆盖物
if(e.features){ // 点击标注
console.log(e)
}
})
this.polyLayer = polyLayer
scene.attachSnapSource(polyLayer.overlayData)
this.scene = scene
this.initMapDraw(scene, 'DRAWING_RECTANGLE', 'rectDraw') // 框选方法
this.initMapDraw(scene, 'DRAWING_CIRCLE', 'circleDraw') // 圆选方法
this.initMapDraw(scene, 'DRAWING_POLYGON', 'polygonDraw') // 多边形
},
// 初始化选择方法
initMapDraw(scene, type, drawName) {
const select = new Select(scene, {
type: DrawingType[type],
isSeries: true,
enableSnap: true,
graphicOpts: {
fillColor: 'yellow'
}
})
// 绘制方法
const draw = {
openSelect: () => {
select.open()
select.addEventListener(OperateEventType.COMPLETE, e => {
// 选择计算
let result = GeoCalculator.intersect(this.polyLayer.overlayData, e.target.overlay.toGeoJSON())
this.polyLayer.resetStyle()
console.log(result)
this.selectedOverlay = result || []
if (result instanceof Array) {
result.forEach(item => {
const activeStyle = { // 选中样式
icon: new BMapGL.Icon(
require('./img/markers_blue2.png'),
new BMapGL.Size(21, 25),
{
anchor: new BMapGL.Size(10, 25)
}
)
}
item.setOptions(activeStyle)
})
}
})
},
closeSelect: () => {
select.close()
this.polyLayer.resetStyle()
this.selectedOverlay = []
}
}
this[drawName] = draw
}
6、参考文档:
百度地图 JavaScript API GL
BMap Draw
7、完整代码:
源码地址:https://gitee.com/jias0606/baiduGLMap_Draw