Leaflet: Resize markers in layer when zoom in

Use setIcon() to change the markers icon in a layer:

var layer = '';//define the layer that contains the markers
map.on('zoomend', function() {
    var currentZoom = map.getZoom();

    //Update X and Y based on zoom level
    var x= 50; //Update x 
    var y= 50; //Update Y         
    var LeafIcon = L.Icon.extend({
        options: {
            iconSize:     [x, y] // Change icon size according to zoom level
        }
    });
    layer.setIcon(LeafIcon);
});

Reference:
http://leafletjs.com/examples/custom-icons/


You have all your markers inside a L.GeoJSON, which is a subclass of L.LayerGroup, so you can use the eachLayer method, like...

all_testptLayer.eachLayer(function(layer) {
    // Do something with each marker inside all_testptLayer
});

You will have to combine this with the setIcon method of L.Marker, and the fact that layers created from a GeoJSON factory have a reference to the GeoJSON data inside their feature property, so something like:

var ar_icon_1 = ...;
var ar_icon_2 = ...;
var ar_icon_1_double_size = ...;
var ar_icon_2_double_size = ...;


map.on('zoomend', function() {
    var currentZoom = map.getZoom();
    if (currentZoom > 12) {
        all_testptLayer.eachLayer(function(layer) {
            if (layer.feature.properties.num < 0.5)
                return layer.setIcon(ar_icon_1);
            else if (feature.properties.num < 1.0)
                return layer.setIcon(ar_icon_2);
        });
    } else {
        all_testptLayer.eachLayer(function(layer) {
            if (layer.feature.properties.num < 0.5)
                return layer.setIcon(ar_icon_1_double_size);
            else if (feature.properties.num < 1.0)
                return layer.setIcon(ar_icon_2_double_size);
        });
    }
});

Further optimizations are possible. The most obvious one is to tore the state of the icon size, in order to not change the icons at each zoom level change (that code will change the icons on every zoom change, most probably to the same icons, wasting CPU time and needless DOM changes). 

Tags:

Leaflet

Zoom