cbll
cbll

Reputation: 7219

Leaflet error: clearLayers is not a function

I'm using a Leaflet offline map with React where I manually load in a countries.js GeoJSON file with every country in the world. I then conditionally color each country depending on data received from this.props.data, which works initially.

However, the issue comes from updating the colors when new this.props.data is coming in.

I have tried managing it in these two components:

componentWillReceiveProps(nextProps) {
    if(this.props.data) {
        let map = this.map;
        console.log(map); // It shows the leaflet object!
        console.log(nextProps.data); // It's logged
        console.log(this.props.data); // Also logged
        if (nextProps.data !== this.props.data) {
            map.clearLayers(); // Error comes here?
            console.log("New data doesn't match old!"); // This logs correctly
        }
    }
},

componentDidUpdate(prevProps, prevState) {
    if(this.props.data){
        let map = this.map;
        if (prevProps.data !== this.props.data) {
            L.geoJson(this.countries, { // from import
            }).addTo(map);
         }
    }
},

What am I doing wrong? The condition is met, if the old data doesn't match the new, the map should clear all layers with clearLayers();. I could understand this error if the map couldn't be found; but I am accessing it with this.map, so it doesn't appear to be a scoping issue.

Upvotes: 5

Views: 6481

Answers (1)

IvanSanchez
IvanSanchez

Reputation: 19069

clearLayers() is a method of L.LayerGroup, not a method of L.Map.

Store the instance of L.GeoJson that you create when running L.geoJson(...), and implement more fine-grained control of when it's added/removed from the map.

Upvotes: 6

Related Questions