问题
Is there any way to modify a single feature's style without modifying default style on select interaction?
Here is a simple piece of code showing my problem and a jsfiddle
Minimal html :
<input type="button" id="switcher" value="Change style"></input>
<div id="map" class="map"></div>
And a simple script :
let vectorLayer = new ol.layer.Vector({
source: new ol.source.Vector({wrapX: false})
});
let map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM({wrapX: false})
}),
vectorLayer,
],
view: new ol.View({
center: ol.proj.transform([9, 44.65], 'EPSG:4326', 'EPSG:3857'),
zoom: 8
})
});
let source = vectorLayer.getSource();
let draw = new ol.interaction.Draw({
source: source,
type: 'Polygon'
});
let selectOnHover = new ol.interaction.Select({
source: source,
condition: ol.events.condition.pointerMove
});
map.addInteraction(draw);
map.addInteraction(selectOnHover);
let fill = new ol.style.Fill({
color: 'rgba(255,0,255,0.4)'
});
let stroke = new ol.style.Stroke({
color: '#00FF00',
width: 5
});
let customStyle = new ol.style.Style({
image: new ol.style.Circle({
fill: fill,
stroke: stroke,
radius: 5
}),
fill: fill,
stroke: stroke
});
document.getElementById('switcher').onclick = function(event) {
let features = source.getFeatures();
if(features.length>0)
features[0].setStyle(customStyle);
}
As you can see by testing on jsfiddle, clicking on the button will correctly change the style of the first drawn feature but also seems to overwritte the default style on hover (here simply a select interaction with condition).
How can I keep the default style on hover while changing my feature style?
回答1:
A style on a feature overrides all style functions (and default styles for interactions, etc). But you could give a feature a customStyle property and use that only in a layer style function instead of a default style, while interactions would continue to use the defaults for interactions.
let defaultFill = new ol.style.Fill({
color: 'rgba(255,255,255,0.4)'
});
var defaultStroke = new ol.style.Stroke({
color: '#3399CC',
width: 1.25
});
var defaultStyles = [
new ol.style.Style({
image: new ol.style.Circle({
fill: defaultFill,
stroke: defaultStroke,
radius: 5
}),
fill: defaultFill,
stroke: defaultStroke
})
];
let vectorLayer = new ol.layer.Vector({
source: new ol.source.Vector({wrapX: false}),
style: function(feature) {
var customStyle = feature.get('customStyle');
return customStyle || defaultStyles;
}
});
...
...
document.getElementById('switcher').onclick = function(event) {
let features = source.getFeatures();
if(features.length>0)
features[0].set('customStyle', customStyle);
}
来源:https://stackoverflow.com/questions/55478263/openlayers-modify-feature-style-without-overwritting-interactions-style