简体   繁体   中英

Using leaflet how can you remove old map tiles added by external plugins?

I have a map with the feature set to change your map tiles in user preferences, the below function is responsible for changing the map tiles dynamically when the user wants to.

  • The actual problem

When I do change the map tiles, for example from CartoDB to OSM in real time, when planning the map viewport, you can see old tiles from CartoDB.

Evidence / Video of this https://i.gyazo.com/702e8e4875bc89c13f41a132dccb78da.mp4

Another thing I should mention, I'm using "leaflet-providers" plugin, for the simple API of adding the tiles to the map.

I did raise an issue on the github repo about my experience of this, but the issue was closed and the author mentioned that this was indeed a leaflet issue, so I've come here for some leaflet.js advice :)

I am aware of how to remove tile layers already, so I need something a little more specific and in relation to my code, here is what I've tried.

//this

self.map.removeLayer(L.tileLayer.provider('OpenStreetMap'))

//this?
//self.map.invalidateSize();

//this??
self.map.invalidateSize();
let self = this;
let mapLayer = self.mapLayer;

if (mapLayer === 'osm') {
    L.tileLayer.provider('OpenStreetMap').addTo(self.map);
}
if (mapLayer === 'cartodb') {
    L.tileLayer.provider('CartoDB').addTo(self.map);
}

//attempt to refresh tiles?
self.map._onResize();
self.map.invalidateSize();

What happens is that whenever you call L.tileLayer.provider('OpenStreetMap') , you get a new instance of a Leaflet Tile Layer.

Therefore when you try removing a Layer from the map with map.removeLayer(L.tileLayer.provider('OpenStreetMap')) , you pass a new layer to your map instance. Because this new Layer is not yet on the map, nothing happens. In particular, the previous Tile Layer remains in place, leading to the situation where you can still see its tiles occasionally.

Simply keep a reference to your initial Layer and use that reference to remove it from the map later on:

var myLayer = L.tileLayer.provider('OpenStreetMap');

myLayer.addTo(map);

// Later...
map.removeLayer(myLayer);

// even simpler alternative:
myLayer.remove();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM