Leaflet custom marker icon scale to zoom

necroface picture necroface · Apr 27, 2016 · Viewed 13.4k times · Source

I use Leaflet to draw an OpenStreetMap and attach it with a custom icon marker

var mymap = L.map('mapid').setView([x, y], 13);

    L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
        attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
        maxZoom: 18,
        id: ID,
        accessToken: accessToken
    }).addTo(mymap);

    var busIcon = new L.Icon({
        iconUrl: 'images/marker/bus.png',
        // shadowUrl: 'images/leaflet/marker-shadow.png',
        iconSize: [12, 12],
        iconAnchor: [12, 41],
        popupAnchor: [1, -34],
        // shadowSize: [41, 41]
    });

    var marker = L.marker([x, y],{icon:busIcon}).addTo(mymap);

    mymap.on('zoomed', function() {
        var currentZoom = mymap.getZoom();
        busIcon = new L.Icon({
            iconUrl: 'images/marker/bus.png',
            iconSize: [mymap.getZoom*2, mymap.getZoom*2],
            iconAnchor: [12, 41],
            popupAnchor: [1, -34],
        });
        marker.setIcon(busIcon);
    });

Now I want to resize my marker icon depending on zoom level. There's something wrong in my above code. What should I do? If marker is a CircleMaker, there is a setRadius function for me to handle this with ease. But in this case the marker is a custom icon, I tried as above and failed. How to fix it?

Answer

Pepe picture Pepe · Sep 2, 2017

As YaFred said, there were some typos like zoomend, but also mymap.getZoom that should be mymap.getZoom()

I made a new answer to this old question to propose a more efficient solution. You can add a className to your icons (see leaflet documentation). This means we can edit the height and width of the icon through css! In your zoomend function, instead of creating a new icon, simply call this JQuery:

var newzoom = '' + (2*(mymap.getZoom())) +'px';
$('#mapid .YourClassName').css({'width':newzoom,'height':newzoom}); 

For larger amounts of markers, this will significantly improve your performance as mentioned in this stackoverflow question: Leaflet custom icon resize on zoom. Performance icon vs divicon