Find Leaflet map object after initialisation

前端 未结 2 1600
被撕碎了的回忆
被撕碎了的回忆 2020-12-31 07:04

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 glob

相关标签:
2条回答
  • 2020-12-31 07:44

    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

    0 讨论(0)
  • 2020-12-31 07:57

    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()
    
    0 讨论(0)
提交回复
热议问题