23

I have an array with ~30k elements and I need to create map with markers for each of them. I use markerclusters and trying to optimize adding moment.

for (var i = 0; i < myItems.length; i++) {
    var item = myItems[i];

    marker = new L.marker([item[2],item[3]], {
        icon: mapOpts.myIcon
    }).bindPopup(item[1]);

    markers.addLayer(marker);

}

Even Google Chrome takes about 40 sec to do this loop. I don't want to see FF's result.

Is there any way to optimize adding many elements to map?

4
  • Curious why are you adding 30k elements? Are those elements all being viewed at once?
    – Alan
    Jun 28, 2013 at 18:29
  • 2
    @Alan yep, when clusterized danzel.github.io/Leaflet.markercluster/example/… Jun 28, 2013 at 18:43
  • Have you found a way to do this without clustering I too have 30+k records I need to display at one time not clustered and deal with non responsive browser issue until it finishes?
    – edjm
    Feb 24, 2021 at 18:28
  • @Elijah hey! a lot of things have changed since 2013, but i will try to ansewr :) I believe i would calculate something on a server side now and don't cluster it in browser. Anyway, it worked pretty acceptable years ago, so now it shall at least not to show worse performance. Check your loop and at what moment you push points into leaflet (check the answers below) Feb 24, 2021 at 23:15

2 Answers 2

18
var markerArray = [];
markerArray.push(L.marker([51.505, -0.09]));
...
var group = L.featureGroup(markerArray).addTo(map);
map.fitBounds(group.getBounds());
2
  • I have an array of lat/long of size 30k so when am plotting the markers like the way you specified but in my case the page gets unresponsive everytime
    – sainanky
    Oct 24, 2017 at 13:31
  • 1
    that's too many markers, you'll need to cluster or use a visualisation like heat map
    – malhal
    Oct 24, 2017 at 19:40
13
var array = [];

for (var i = 0; i < myItems.length; i++) {
    var item = myItems[i];

    marker = new L.marker([item[2],item[3]], {
        icon: mapOpts.myIcon
    }).bindPopup(item[1]);

    array.push(marker);
}

markers.addLayers(array);

See the docs for more details.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.