A
A
Alexander2014-09-23 18:59:53
leaflet
Alexander, 2014-09-23 18:59:53

How to resize a large number of icons on a leaflet map?

I have a map, it has markers with svg icons. When the map is scaled, the size of the icons also changes. At the moment, I resize each icon and call the setIcon method on each marker to re-set the icon.
This is bad because you have to remember which icon belongs to which marker and I'm not sure if this is efficient in terms of performance.
I have an array of icons. Large, 200 elements. Looks like this:

var icons = [
    'one' : L.icon({
        iconUrl:    '/icons/one.svg',
        iconSize:   [24, 24],
        iconAnchor: [12, 24],
    }),
    'etc' : L.icon({
        iconUrl:    '/icons/etc.svg',
        iconSize:   [24, 24],
        iconAnchor: [12, 24],
    }),
    ...
]

Next, I create markers:
var markers = [];      

function addMarker(icon, lat, lng) {
    var marker = L.marker([lat, lng], {
        icon: icons[icon],
        draggable : true
    }).addTo(map);
    marker.icon = icons[icon];
    markers.push(marker);
}

addMarker('one', 0, 0)
....

In the end, I calculate the modifier on the resize event and change the size of the icons and resize them:
map.on('zoomend', function() {
    var currentZoom = map.getZoom();
    var modifier = 1;
    switch (currentZoom) {
       // считаем modifier
    }
    
    // ресайзим все иконки
    for (var i in icons) {
        icons[i].options.iconSize = [size * modifier, size * modifier];
        icons[i].options.iconAnchor = [size / 2 * modifier, size * modifier];
    }
    
   // реассайню все иконки
    for (var i in markers) {
          markers[i].setIcon(markers[i].icon);
    }
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
My joy, 2014-09-23
@t-alexashka

I advise you to use divIcon instead of Icon and assign the same css class to all. They already manage it. I hope I understood correctly.
In principle, you can also assign a css class to Icon.
It would be much easier to call something like
$('.my-lf-icon').css('...','...')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question