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?

Egor Sazanovich
  • 4,979
  • 5
  • 23
  • 37
  • Curious why are you adding 30k elements? Are those elements all being viewed at once? – Alan Jun 28 '13 at 18:29
  • 2
    @Alan yep, when clusterized http://danzel.github.io/Leaflet.markercluster/example/marker-clustering-realworld.50000.html – Egor Sazanovich Jun 28 '13 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 '21 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) – Egor Sazanovich Feb 24 '21 at 23:15

2 Answers2

18
var markerArray = [];
markerArray.push(L.marker([51.505, -0.09]));
...
var group = L.featureGroup(markerArray).addTo(map);
map.fitBounds(group.getBounds());
malhal
  • 26,330
  • 7
  • 115
  • 133
  • 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 '17 at 13:31
  • 1
    that's too many markers, you'll need to cluster or use a visualisation like heat map – malhal Oct 24 '17 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.

L. Sanna
  • 6,482
  • 7
  • 33
  • 47