Find Leaflet map object after initialisation

Joeytje50 picture Joeytje50 · Jul 31, 2017 · Viewed 7.9k times · Source

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?

Answer

ghybs picture ghybs · Aug 1, 2017

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