Skip to content Skip to sidebar Skip to footer

Leaflet: Add Same Layer To Two Different Maps

I am displaying two different leaflet maps in the same page. After a certain event. I want a Polyline to appear on both of them. I would like to avoid, if possible, to create a cop

Solution 1:

As geocodezip mentioned in a comment, adding a polyline to a map sets the polyline object's this._map instance variable. Therefore, there is no way to have the object rendered on both maps with the way in which it is currently implemented.

You can view the relevant source code here.

Solution 2:

You can't add the same layer to multiple Leaflet maps. But I had a similar problem using a more complex GeoJSON layergroup and ultimately solved it by getting the GeoJSON object from the layer using toGeoJSON() and using it to create a new layer for the second map. For a simple polyline, you could use getLatLngs(). So:

var line_coordinates = [[1,2],[3,4]];
var my_polyline = L.polyline(line_coordinates);
my_polyline.addTo(map1);
var new_polyline = L.polyline(line_coordinates);
new_polyline.addTo(map2);

should work, as would:

var line_coordinates = [[1,2],[3,4]];
var my_polyline = L.polyline(line_coordinates);
my_polyline.addTo(map1);
var my_polyline_latlngs = my_polyline.getLatLngs();
var new_polyline = L.polyline(my_polyline_latlngs);
new_polyline.addTo(map2);

Post a Comment for "Leaflet: Add Same Layer To Two Different Maps"