OL3: how to change the selected function style based on scaling?
I am using the following code to change the radius of the Circle marker based on the zoom level:
//add the layer to the map
map.addLayer(vectorLayer);
//add selection interactivity, using the default OL3 style
var select = new ol.interaction.Select();
map.addInteraction(select);
map.getView().on('change:resolution', function(evt) {
var zoom = map.getView().getZoom();
var radius = zoom / 2 + 1;
var newStyle = new ol.style.Style({
image: new ol.style.Circle({
radius: radius,
fill: new ol.style.Fill({color: 'red'}),
stroke: new ol.style.Stroke({color: 'black', width: 1})
})
})
vectorLayer.setStyle(newStyle);
});
But the problem is that if I select a feature on the map, the selected / high level style does not change when the map scale is changed. How can I dynamically change the style of the selected features based on scaling / resolution?
Clarification . The above code already works for changing the radius of all functions on the map, but in addition to that I also need the radius of the selected functions to change. Both selected and unselected features should change depending on the zoom level.
source to share
You need to set the function style
to the interaction constructor, for example:
var select = new ol.interaction.Select({
style: function(feature, resolution){
var zoom = map.getView().getZoom();
var radius = zoom / 2 + 1;
console.info(radius);
var newStyle = new ol.style.Style({
image: new ol.style.Circle({
radius: radius,
fill: new ol.style.Fill({color: 'red'}),
stroke: new ol.style.Stroke({color: 'black', width: 1})
})
});
return [newStyle];
}
});
A working demo .
source to share
Use the scale bar to resize the radius as you zoom in.
map.getCurrentScale = function () {
//var map = this.getMap();
var map = this;
var view = map.getView();
var resolution = view.getResolution();
var units = map.getView().getProjection().getUnits();
var dpi = 25.4 / 0.28;
var mpu = ol.proj.METERS_PER_UNIT[units];
var scale = resolution * mpu * 39.37 * dpi;
return scale;
};
map.getView().on('change:resolution', function(evt){
var divScale = 60;// to adjusting
var radius = map.getCurrentScale()/divScale;
feature.getStyle().getGeometry().setRadius(radius);
})
source to share