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.
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 :-)
the best way
map.off();
map.remove();
You should add map.off(), it also works faster, and does not cause problems with the events
For refresh leaflet map you can use this code:
this.map.fitBounds(this.map.getBounds());
Try map.remove();
before you try to reload the map. This removes the previous map element using Leaflet's library (instead of jquery's).
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.