3
votes

I'm using Leaflet to visualize point data and I'm trying to change the radius of circle according to the zoom level.

The more the user is zoomed in, the larger the radius.

Work in progress available here.

Here's what I have so far.

The first line sets the initial radius:

var damsRadius = 2;

Then I have a zoomend event to get the zoom level and then use that zoom level to determine the new radius:

map.on('zoomend', function(e) {
    var currentZoom = map.getZoom();
    console.log("Current Zoom" + " " + currentZoom);
    if (currentZoom <= 6) {
        damsRadius = 2;
    } else {
        damsRadius = 6;
    }
    console.log("Dams Radius" + " " + damsRadius);
});

I set the radius as part of the style object:

function damsStyle(feature) {
    return {
      fillOpacity: 0.8,
      fillColor: getColor(feature.properties.mainuse),
      weight: 1,
      opacity: 1,
      color: '#e0e0e0',
      radius: damsRadius // HERE IS WHERE I SET THE RADIUS
    };
}

and then add the whole kit to the map using pointToLayer later on:

pointToLayer: function (feature, latlng) {
    return L.circleMarker(latlng, damsStyle(feature));
} 

Everything works swimmingly according to the console. Zooming in and out shows that the value for damsRadius is changing as expected.

The trouble is, though, the radius of the points on the map doesn't change. So, somewhere along the way something isn't getting communicated.

I tried the same trick with L.circle but it didn't work either. Do I need to use clearLayers function and redraw every time I change the zoom level?

That seems a bit excessive.

Advice?

1

1 Answers

3
votes

You need to reset the style once the zoom changes.

Simply add the below line in your map.on('zoomend') function

timeline.setStyle(damsStyle)

so, your function would be like this

map.on('zoomend', function(e) {
    var currentZoom = map.getZoom();
    console.log("Current Zoom" + " " + currentZoom);
    if (currentZoom <= 6) {
      damsRadius = 2;
    } else {
    damsRadius = 6;
    }
    console.log("Dams Radius" + " " + damsRadius);
    timeline.setStyle(damsStyle)//add this line to change the style
});

Note: You might need to change the scope of your timeline variable in order to access it in zoomend function.