Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 copy and keep two different variables.

I am trying yo use the following:

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

However, if I run the above code, the Polyline will be displayed only on the map2.

Afterwords, I will need to change again its coordinates to some new_line_coordinates, and I will run the following:

my_polyline.setLatLngs(new_line_coordinates);
my_polyline.redraw();

The polyline should now appear updated to the new coordinates. However, again, it appears only on map2.

What am I doing wrong? Is it possible to achieve what I am trying to do?

like image 982
Marco Avatar asked Oct 23 '25 17:10

Marco


2 Answers

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.

like image 113
Pwnosaurus Avatar answered Oct 26 '25 07:10

Pwnosaurus


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);
like image 37
northlandiguana Avatar answered Oct 26 '25 05:10

northlandiguana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!