bramb84
bramb84

Reputation: 375

OL3: how to modify selected feature style based on zoom?

I use the following code to modify the radius of a 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 I have is that if I select a feature on the map, the selected/highlighed style does not change when the map zoom changes. How can I also dynamically modify the style of selected features based on zoom/resolution?

Clarification The code above already works for changing radius of all features on the map, but in addition to that I also need the radius of selected features to change. Both selected and unselected features should be changing based on zoom level.

Upvotes: 5

Views: 6120

Answers (3)

Tareq boudalia
Tareq boudalia

Reputation: 73

Use the scale base for the radius resizing when zoomed.

 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);
    })

Upvotes: 1

Jonatas Walker
Jonatas Walker

Reputation: 14150

You need to set a style function on interaction constructor like:

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.

Upvotes: 4

MichaelJS
MichaelJS

Reputation: 193

Did you set the radius in that other style (selected/highlighed), too?

Upvotes: 0

Related Questions