因为是BMap
和 openlayers
一起做,所以对于所有功能都是对标百度地图离线,这不,前不久刚弄好了百度地图的电子围栏功能,然后就开始了openlayer
的了,不过总体来说要比前一次弄轻松很多,因为逻辑什么的都是一样的,就是画图可能不一样,所以也是看了一波API
然后先把绘图功能搞出来。其余的因为也涉及公司业务就不多bb了。有兴趣的也可以看看百度地图的绘图:
百度地图API(四)电子围栏—DrawingManager
话不多说,代码献上,api文档说明我就不搬了
功能
class drawFence {
constructor(props) {
//这里初始化class的时候需要传map对象进来
this.map = props;
this.source;
this.fenceLayer;
this.draw;
//样式
this.fenceStyle = new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)'
}),
stroke: new ol.style.Stroke({
color: '#ffcc33',
width: 2
}),
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: '#ffcc33'
})
})
})
this.init()
}
init() {
//临时图层的数据源
this.source = new ol.source.Vector();
//新建临时图层,并设置临时图层渲染各种要素的样式
this.fenceLayer = new ol.layer.Vector({
source: this.source,
style: this.fenceStyle
});
this.map.addLayer(this.fenceLayer)
}
drawingEnd(evt) {
let geo = evt.feature.getGeometry()
let type = geo.getType(); //获取类型
console.log(geo)
//根据不同的类型执行不同的操作
const handle = {
'Circle': () = > {
//获取中心点和半径
let center = geo.getCenter()
let radius = geo.getRadius()
console.log(center, radius)
},
'Polygon': () = > {
//获取坐标点
let points = geo.getCoordinates()
console.log(points)
},
'LineString': () = > {
let points = geo.getCoordinates()
console.log(points)
}
}
if (handle[type]) handle[type]()
this.closeDraw()
}
closeDraw() {
this.map.removeInteraction(this.draw);
}
//画图
drawingFence(type) {
this.draw = new ol.interaction.Draw({
source: this.source, //设置要素源,绘制结束后将绘制的要素添加到临时图层
type: type, //绘制的类型
});
this.map.addInteraction(this.draw);
const that = this;
//绘图结束事件回调
this.draw.on('drawend', function (evt) {
that.drawingEnd(evt)
});
}
}
初始化
这里因为我已经知道自己的map对象,所以我就直接复制过来了,反正大家明白mapTools.map
就是你地图初始化后的map
对象
const fence = new drawFence(mapTools.map) //电子围栏
使用
$('#polygonFence').on('click', function () {
fence.drawingFence('Polygon')
})
$('#circleFence').on('click', function () {
fence.drawingFence('Circle')
})
$('#polylineFence').on('click', function () {
fence.drawingFence('LineString')
})