Skip to content Skip to sidebar Skip to footer

Find Leaflet Map Object After Initialisation

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 varia

Solution 1:

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 addInitHookconstructor 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

Solution 2:

You can access the map from the global array created by the mediawiki extension.

Es: for accessing the first map of the page

window.maps.leafletList[0].map.getCenter()

Post a Comment for "Find Leaflet Map Object After Initialisation"