Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leaflet custom marker icon scale to zoom

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?

like image 771
necroface Avatar asked Apr 27 '16 05:04

necroface


2 Answers

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

like image 131
Pepe Avatar answered Oct 23 '22 17:10

Pepe


You have a typo: zoomed should be zoomend

map.on('zoomend', function() {
});

http://plnkr.co/edit/72ywrO8pgmmxLW6Y8mcL?p=preview

Apart from that, I would create and keep the icons out of the zoomend callback.

As it is, your code is creating an icon each time zoom is changing.

like image 3
YaFred Avatar answered Oct 23 '22 17:10

YaFred