The function getCountryBorders() updates the map by drawing the desired country border every time the function is run. However, it just adds each country border to the current layer, rather than replacing the old border.
How can I clear the current layer each time the function is called?
const getCountryBorders = function() {
$.ajax({
url: "libs/php/getCountryBorders.php",
type: 'POST',
dataType: 'json',
success: function(result) {
const countries = result["data"]["features"];
function countryFilter(feature) {
if (feature.properties.iso_a2 === countryCode) return true
}
const borderStyle = {
"color": "red"
}
borderLayer = L.geoJson(countries, {
filter: countryFilter,
style: borderStyle
}).addTo(map);
},
error: function(jqXHR, textStatus, errorThrown) {
}
})
}
Since your borderLayer is in global scope, a very easy solution is to remove it from the map just before reassigning it:
if (borderLayer) {
borderLayer.remove();
}
borderLayer = L.geoJson(countries).addTo(map);