Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ol3 / Openlayers3: change radius of circle when zoomed

Tags:

openlayers-3

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);
});
like image 642
bramb84 Avatar asked Jun 24 '15 10:06

bramb84


1 Answers

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.

like image 162
Jonatas Walker Avatar answered Dec 07 '22 23:12

Jonatas Walker