初始化后查找 Leaflet 地图对象

Find Leaflet map object after initialisation

我正在尝试使用 Leaflet library 更改已由另一个脚本初始化的地图上的某些内容。这个其他脚本没有将地图对象存储在全局变量中,也没有存储在我可以使用我的脚本访问的任何其他位置。所以目前我的页面上有一张地图,但我没有地图对象。

我想做的是检索已初始化地图的对象,对其进行更改。例如,如果存在函数 L.getMap('myID') 我想使用这样的方法来检索链接到容器 myID.

的地图对象

TL;DR:有没有办法使用容器的 id 获取已初始化的传单地图的地图对象?

您可以从 mediawiki 扩展创建的全局数组访问地图。

Es: 用于访问页面的第一张地图

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

郑重声明,如果您有可能在地图初始化之前注入/执行一些 JS 代码(即在 "other script" 执行之前),您可以非常轻松地自定义 Leaflet 以保留对每个人都创建了地图。

例如在 L.Map class:

上使用 addInitHook constructor hook
// 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();

演示:https://plnkr.co/edit/mywpSbfRPFOnJ8c1RNsZ?p=preview