Using TURF js, you can determine if your point is inside a polygon. "turf.inside(point, polygon)". Basically using the eachLayer function, you can loop through each poly and determine if the point is inside. If it is turf.inside will return TRUE.
Working example: The JSON file I used. http://www.gistechsolutions.com/leaflet/DEMO/Search/usa.json
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://npmcdn.com/@turf/turf/turf.min.js"></script>
<style>
#map {
width: 800px;
height: 600px;
border: 1px solid black;
z-index: 0;
}
</style>
</head>
<body>
<div id="map" ></div>
</div>
<script>
var url = 'usa.json'; // my GeoJSON data source, in this case a static file not a live PHP data feed.
//'http://www.gistechsolutions.com/leaflet/DEMO/Search/usa.json'
var map = L.map('map').setView([47.7541, -107.05078], 3);
var osm=new L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png',{
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'});
var OpenStreetMap_BlackAndWhite = L.tileLayer('http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
});
OpenStreetMap_BlackAndWhite.addTo(map);
// Set style function that sets fill color property
function style(feature) {
return {
fillColor: 'green',
fillOpacity: 0.5,
weight: 2,
opacity: 1,
color: '#ffffff',
dashArray: '3'
};
}
// Null variable that will hold layer
var stateLayer = L.geoJson(null, { style: style});
$.getJSON(url, function(data) {
stateLayer.addData(data);
});
stateLayer.addTo(map);
map.on('click',function(e){
lat = e.latlng.lat;
lon = e.latlng.lng;
ProcessClick(lat,lon)
});
var theMarker;
var selPoly = [];
function ProcessClick(lat,lon){
if (theMarker != undefined) {
map.removeLayer(theMarker);
};
theMarker = L.marker([lat,lon]).addTo(map);
stateLayer.eachLayer(function (layer) {
isInside =turf.inside(theMarker.toGeoJSON(), layer.toGeoJSON());
if (isInside){
selPoly.push(layer.feature);
console.log(layer.feature.properties.STATE_NAME);
}
})
var newgeojsonLayer = L.geoJson(selPoly, {
color: 'orange',
fillOpacity: .5,
opacity: 1
}).addTo(map);
}
var baseMaps = {
"Open Street Map": osm,
"OSM B&W":OpenStreetMap_BlackAndWhite
};
var overlayMaps = {
"USA":stateLayer
};
//Add layer control
L.control.layers(baseMaps, overlayMaps).addTo(map);
</script>
</body>
</html>