refresh leaflet map: map container is already initialized

后端 未结 17 891
鱼传尺愫
鱼传尺愫 2020-11-27 04:16

I have a page where given a select to the user he can switch the leaflet map I show.

After a initial leaflet map load, my problem is when i want to refresh the map.

相关标签:
17条回答
  • well, after much seeking i realized it's well documented at http://leafletjs.com/examples/layers-control.html

    i've ended not repainting the map, but print it once and repaint the points on each new ajax call, so the problem was how to clean up the old points and print only the new ones. i've ended doing this:

    var point = L.marker([new_marker[0], new_marker[1]]).addTo(map).bindPopup('blah blah');
    points.push(point); 
    //points is a temporary array where i store the points for removing them afterwards
    

    so, at each new ajax call, before painting the new points, i do the following:

    for (i=0;i<points.length;i++) {
      map.removeLayer(points[i]);
    }
    points=[];
    

    so far, so good :-)

    0 讨论(0)
  • 2020-11-27 04:46

    the best way

    map.off();
    map.remove();
    

    You should add map.off(), it also works faster, and does not cause problems with the events

    0 讨论(0)
  • 2020-11-27 04:47

    For refresh leaflet map you can use this code:

    this.map.fitBounds(this.map.getBounds());

    0 讨论(0)
  • 2020-11-27 04:51

    Try map.remove(); before you try to reload the map. This removes the previous map element using Leaflet's library (instead of jquery's).

    0 讨论(0)
  • 2020-11-27 04:52

    If you don't globally store your map object reference, I recommend

    if (L.DomUtil.get('map-canvas') !== undefined) { 
       L.DomUtil.get('map-canvas')._leaflet_id = null; 
    }
    
    

    where <div id="map-canvas"></div> is the object the map has been drawn into.

    This way you avoid recreating the html element, which would happen, were you to remove() it.

    0 讨论(0)
提交回复
热议问题