實現(xiàn)地圖框形選點、圓形選點、多邊形選點,并修改選中點的顏色,主要使用BMap Draw
效果圖:

效果圖
1、引入百度地圖js,引入的百度api所用的key請去其官網(wǎng)申請并替換使用:
<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、按需引入相關(guān)插件
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() // 定位當(dāng)前城市
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) // 創(chuàng)建標(biāo)注
polyLayer.addOverlay(marker.toGeoJSON())
polyLayer.addEventListener('click', (e) =>{
console.log(polyLayer.pickOverlays(e)) // 判斷是否點擊覆蓋物
if(e.features){ // 點擊標(biāo)注
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