I'm trying to change some things on a map that is already initialised by another script, using the Leaflet library. This other script did not store the map-object in a global variable, or in any other location I can access with my script. So currently there is a map on my page, but I don't have the map object.
What I'd like to do is to retrieve the object of an already-initialised map, to make changes to it. For example, if there'd exist a function L.getMap('myID')
I'd like to use such a method to retrieve the map object linked to the container myID
.
TL;DR: Is there a way to get a map object of an already-initialised leaflet map, using the id of the container?
To refresh leaflet map when map container is already initialized with JavaScript, we call the off and remove methods before reloading the map. map. off(); map. remove();
Use the addPopups() function to add standalone popup to the map. A common use for popups is to have them appear when markers or shapes are clicked. Marker and shape functions in the Leaflet package take a popup argument, where you can pass in HTML to easily attach a simple popup.
For the record, in case you have the possibility to inject / execute some JS code before the map is initialized (i.e. before the "other script" executes), you can very easily customize Leaflet to keep a reference to each created maps.
E.g. using the addInitHook
constructor hook on L.Map
class:
// Before map is being initialized.
var mapsPlaceholder = [];
L.Map.addInitHook(function () {
mapsPlaceholder.push(this); // Use whatever global scope variable you like.
});
// "Other script", can be in its own separate <script> and JS file.
L.map('mapId'); // The map object is pushed into `mapsPlaceholder` array.
// Then retrieve the map object to further manipulate the map.
var map = mapsPlaceholder.pop();
Demo: https://plnkr.co/edit/mywpSbfRPFOnJ8c1RNsZ?p=preview
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With