Enrico Casanova
Enrico Casanova

Reputation: 51

Remove geoJSON from Leaflet map

I have a function who retrieves a JSON with earthquakes data, that I add to a Leaflet map, that retrieves the JSON again after 10 seconds (for refreshing data):

function fetchQuake() {
        fetch('https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson')
        .then(function(res) {
            if (res.ok === true) {
                return res.json();
            } else {
                alert('Geojson request failed.');
            }
        })
        .then(function(quake) {
                L.geoJSON(quake, {
                    style: function(feature) {
                        return feature.properties && feature.properties.style;
                    },
                    onEachFeature: onEachFeature,
                    pointToLayer: function(feature, latlng) {
                        return L.circleMarker(latlng, {
                            radius: 8,
                            fillColor: "#ff7800",
                            color: "#000",
                            weight: 1,
                            opacity: 1,
                            fillOpacity: 0.8
                        });
                    }
                }).addTo(map);

            myQuakeTimeout = setTimeout(function() {
                fetchQuake();
            }, 10000);
        });
}

And a function who clears the map from these points:

function clearQuake() {
    clearTimeout(myQuakeTimeout);
    L.geoJSON().clearLayers();
}

With these code, the timeout stops, but the earthquakes points don't go away from the map, what is the problem?

Upvotes: 1

Views: 3255

Answers (1)

Jordi Nebot
Jordi Nebot

Reputation: 3401

With this code, your clearQuake() function is never called, so L.geoJSON().clearLayers() is never executed.

That's the reason your points don't go away from the map.

If you want to remove the previous points before adding the new fetched ones, you could do something like:

/* ... */
.then(function(quake) {

    L.geoJSON().clearLayers();

    L.geoJSON(quake, {
        /* ... */
    }).addTo(map);

    myQuakeTimeout = setTimeout(fetchQuake, 10000);
});

Upvotes: 1

Related Questions