Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 340
Steve Bennett Avatar asked Aug 04 '26 01:08

Steve Bennett


1 Answers

  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).

like image 128
Liedman Avatar answered Aug 05 '26 15:08

Liedman



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!