在实际开发中,有时经常会碰到选择图形高亮显示和移动图形的操作,在Openlayers
中提供了很方便的API
,如果点击图形后,需要对选择的图形进行高亮显示,可以使用ol.interaction.Select
来添加地图交互操作,给ol.interaction.Select
指定一个事件就可以执行单击高亮或者鼠标移动时高亮。还有当选择图形后,如果需要对移动图形,可以使用ol.interaction.Translate
来添加地图交互操作,添加该交互事件后,选择图形后再按钮Alt
键,就可以拖动选择的图形了,具体的代码如下所示:
class SelectUtil{
constructor(map){
this.map = map
}
//添加单击选择
addClickSelect(){
this._initInteraction(new ol.interaction.Select({
condition:ol.events.condition.click
}))
return this
}
//添加鼠标移动选择
addHoverSelect(){
this._initInteraction(new ol.interaction.Select({
condition:ol.events.condition.pointerMove,
multi:true
}))
return this
}
//添加单击选择
addSingleClickSelect(){
this._initInteraction(new ol.interaction.Select())
return this
}
//添加移动事件
addTranslate(){
if(!this.select){
this.addClickSelect();
}
var translate= new ol.interaction.Translate({
features: this.select.getFeatures()
});
this.map.addInteraction(translate)
}
//添加框选要素
addBoxSelection(vectorSource){
if(!this.select){
this.addClickSelect();
}
var selectedFeatures = this.select.getFeatures()
var dragBox = new ol.interaction.DragBox({
condition: ol.events.condition.platformModifierKeyOnly
})
this.dragBox = dragBox;
this.map.addInteraction(dragBox)
dragBox.on('boxend',function(event){
var extent = dragBox.getGeometry().getExtent();
vectorSource.forEachFeatureIntersectingExtent(extent, function(feature) {
selectedFeatures.push(feature);
});
})
dragBox.on('boxstart',function(event){
selectedFeatures.clear();
})
dragBox.on('',function(event){
})
}
//回调
then(fn){
this.callback = fn
}
_initInteraction(select){
if(this.select){
this.map.removeInteration(this.select)
}
this.select = select
this.map.addInteraction(select)
var self = this
select.on('select', function(e) {
var selected = e.selected
if(self.callback){
self.callback(selected)
}
})
}
}