ol3 / Openlayers3: change radius of circle when zoomed
Asked Answered
C

2

6

I have a vector layer with the style currently defined as:

var styles = new ol.style.Style({
image: new ol.style.Circle({
  radius: 4,
  fill: new ol.style.Fill({color: 'red'}),
  stroke: new ol.style.Stroke({color: 'black', width: 1})
})

I want the radius to change dynamically, based on the map zoom level - something like:

radius:(zoom/2)+1

How would I go about doing so?

UPDATE: Jonatas' comment helped steer me in the right direction. I ended up using the following:

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);
});
Corr answered 24/6, 2015 at 10:56 Comment(0)
S
6

You can listen to resolution changes:

map.getView().on('change:resolution', function(evt){
    //according to http://openlayers.org/en/v3.6.0/apidoc/ol.View.html
    // I think this is not true for any scenario
    //40075016.68557849 / 256 / Math.pow(2, 28) = 0.0005831682455839253

    var resolution = evt.target.get(evt.key),
        resolution_constant = 40075016.68557849,
        tile_pixel = 256;

    var result_resol_const_tile_px = resolution_constant / tile_pixel / resolution;

    var currentZoom = Math.log(result_resol_const_tile_px) / Math.log(2);
    console.info(currentZoom, resolution);

    //now find your features and apply radius
    feature.getStyle().getGeometry().setRadius(radius);
});

Note that I'm converting resolution to zoom but this is just a curiosity. You can get rid of it and set radius based on resolution.

Saiff answered 24/6, 2015 at 14:26 Comment(1)
Thank you -- this helped me get started.Corr
P
4

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);
});
Permutation answered 30/11, 2016 at 13:37 Comment(4)
What's 39.37 in the scale calculation?Surreptitious
39.37 for getting inches per meterPermutation
@Tareqboudalia Works great, exactly how it's suposed to.Anode
@Anode Thanks and i'll be happy if you vote on the answerPermutation

© 2022 - 2024 — McMap. All rights reserved.