Polygon selection based on marker position in leaflet

On the map, I have an added layer with polygons and one marker on another layer. When I click anywhere, the marker moves to that location and the polygon is selected. The marker has the ability to drag across the map, but just when I drag it, the polygon selection does not appear. How to do this?


var osm = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
});

var map = new L.Map('map', {
    'center': [51, 17],
    'zoom': 6,
    'layers': [osm],
});

var selected;


var marker
marker = L.marker([51, 17], {
    draggable: true
}).addTo(map);





var geoJsonLayer2
geoJsonLayer2 = L.geoJson( polygons ,{
style: {
fillColor: "#1ED100",
color: "orange",
fillOpacity: 0.0,
opacity: 0.0,
},

})
.on('click', function (e) {
// Check for selected
if (selected) {
// Reset selected to default style
e.target.resetStyle(selected)
}
// Assign new selected
selected = e.layer
// Bring selected to front
selected.bringToFront()
// Style selected
selected.setStyle({
'color': 'red',
'opacity': 1,
})
})
.addTo(map);



marker.on('dragend', function (e, feature) {
    updateLatLng(marker.getLatLng().lat, marker.getLatLng().lng);
});

map.on('click', function (e) {
    marker.setLatLng(e.latlng);
    updateLatLng(marker.getLatLng().lat, marker.getLatLng().lng);
});



function updateLatLng(lat, lng, reverse) {
    if (reverse) {
        marker.setLatLng([lat, lng]);
        map.panTo([lat, lng]);
    } else {
        document.getElementById('lat').value = marker.getLatLng().lat.toFixed(10);
        document.getElementById('long').value = marker.getLatLng().lng.toFixed(10);
        map.panTo([lat, lng]);

        document.getElementById("lat").value = lat.toFixed(10);
        document.getElementById("long").value = lng.toFixed(10);
    }
}



enter image description here

view after clicking on the polygon

enter image description here

view after shifting the marker

Back to Top