Tenz Tenz - 1 month ago 16
Javascript Question

Leaflet: How to add multiple markers onto featureGroup

I am trying to do something like : https://github.com/IvanSanchez/Leaflet.Polyline.SnakeAnim/blob/master/demo-group.gif
where I have multiple markers.

In the example code https://github.com/IvanSanchez/Leaflet.Polyline.SnakeAnim/blob/master/demo-group.html
each location has been manually added using

var trd = [63.5, 11],
mad = [40.5, -3.5],
lnd = [51.5, -0.5],
ams = [52.3, 4.75],
vlc = [39.5, -0.5];

var route = L.featureGroup([
L.marker(trd),
L.polyline([trd, ams]),
L.marker(ams),
L.polyline([ams, lnd]),
L.marker(lnd),
L.polyline([lnd, mad]),
L.marker(mad),
L.polyline([mad, vlc]),
L.marker(vlc)
]);


My question is, if I have many markers (e.g. 500 markers), how can I create the route without manually adding each marker and polyline to the L.featureGroup.

var bounds = new L.LatLngBounds();
for (var i = 0; i < mTool.length; i++) {
var loc = new L.LatLng(mTool[i].lat, mTool[i].lon);
bounds.extend(loc);
var marker = new L.Marker(loc);
map.addLayer(marker);
}
map.fitBounds(bounds);

Answer

This is easily done by looping through an array of markers, as you rightly hinted at it. The code could be as below:

var markers = [[63.5, 11],
        [40.5, -3.5],
        [51.5, -0.5],
        [52.3, 4.75],
        [39.5, -0.5]];

var route = L.featureGroup().addTo(map);

var n = markers.length;

for (var i = 0; i < n-1; i++) {
            var marker = new L.Marker(markers[i]);
            var line = new L.polyline([markers[i],markers[i+1]]);
            route.addLayer(marker);
            route.addLayer(line);
};
route.addLayer(new L.Marker(markers[n-1]));

map.fitBounds(route.getBounds());

I created a working example on gist (here).

Comments