Search code examples
javascriptdomleafletintrospection

Find Leaflet map objects present on page, without a variable reference


I have an idea for a browser plugin which would manipulate Leaflet maps on third-party sites. But I'm stuck on a simple thing: I'm not sure how to discover Leaflet map DOM elements on a page, and then access the associated Leaflet map object.

  1. Is $('.leaflet-container') a reliable way to find all map objects?

  2. How to actually access the map object from that object, so I can do something like: $('.leaflet-container').eachLayer(...), which doesn't work.

This question is essentially the same as How can I get a leaflet.js instance using only a DOM object?, but the answer there was a workaround which doesn't help.


Solution

    1. Yes, that should be sufficient, although it's not a documented behavior and could at least theoretically change in future versions of Leaflet
    2. There's no way to do this. The reference to the map is owned by the code creating the map, and it could have discarded it or might be storing it in a location you do not have access to. Leaflet itself does not store a reference to the map anywhere where you can access it

    On a side note, it is my opinion that you should rather let users of your code explicitly pass references to you, rather than you trying to automatically find references. See for example the inversion of control principle, where the caller supplies dependencies; Law of Demeter is also somewhat applicable - don't pry into other codes internals (unless you really, really have to).