I want to draw markers and borders of selected region. And Sometimes when I change it, it works good, but sometimes markers moves to new region and there are still old borders (bad image). How can I solve it? I think problem is in updateMAP function
<html lang="en">
<body>
<label for="citySelect">Выбор региона:</label>
<select id="regionSelect" name="region">
{% for region in regions %}
<option value="{{ region }}">{{ region }}</option>
{% endfor %}
</select>
<div id="map"></div>
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
<script src="https://cdn.jsdelivr.net/npm/leaflet.heat/dist/leaflet-heat.js"></script>
<script>
var map;
var data = {{ data|tojson }};
var markers = []
var heatLayer;
var geojsonLayer;
function updateMap() {
var selectedRegion = document.getElementById("regionSelect").value;
clearMarkers();
var filteredData = data.filter(function(item) {
return item["ФИАС Регион"] === selectedRegion;
});
var heatmapData = filteredData.map(function(item) {
return [item['Координаты: широта'], item['Координаты: долгота'], item['Страховая сумма Кумуляция']];
});
addMarkers(filteredData);
if (heatLayer) {
map.removeLayer(heatLayer);
}
heatLayer = L.heatLayer(heatmapData, { radius: 25 }).addTo(map);
fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${selectedRegion}&polygon_geojson=1`)
.then(response => response.json())
.then(data => {
if (data.length > 0 && data[0].geojson) {
if (geojsonLayer) {
map.removeLayer(geojsonLayer);
}
geojsonLayer = L.geoJSON(data[0].geojson).addTo(map);
}
})
.catch(error => console.error('Error fetching region data:', error));
}
function initMap() {
map = L.map('map').setView([0, 0], 2);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
}
function clearMarkers() {
for (var i = 0; i < markers.length; i++) {
map.removeLayer(markers[i]);
}
markers = [];
}
function addMarkers(data) {
for (var i = 0; i < data.length; i++) {
var marker = L.marker([data[i]['Координаты: широта'], data[i]['Координаты: долгота']]).addTo(map);
markers.push(marker);
}
}
document.getElementById("regionSelect").addEventListener("change", updateMap);
</script>
<script>initMap();</script>
</body>
</html>
my html code is above. also there is part of python code of fastapi connection, but i think it doesn’t matter now