[GIS] Select feature in GeoJSON layer by location

geojsonleafletselect-by-location

I have a Leaflet slippy map with a GeoJSON layer loaded. I can click this layer manually and read attribute values from it. Now my question is:

How can I read attributes of said layer without selecting it? I'd like to do that by using my current location. I've managed to check if my location is within the GeoJSON layer with d3.js, but can't figure out how to select attributes of the respective feature. Which JavaScript client side framework could be used to face this problem?

code from d3.js console.log(d3.geoContains(jsondata[map.getCenter().lng,map.getCenter().lat]));

returns boolean answer.

Best Answer

One possible approach could consist into firing some suitable events (e.g. mouseover, mouseout) when the center of the map stops changing (moveend) using a point-in-polygon logic (e.g. leaflet-pip or leaflet.cheaplayerat). For instance, considering the choropleth tutorial and using leaflet-pip, the following code should do the task:

map.on('moveend', function () { 
  var latlngPoint = map.getCenter();
  geojson.eachLayer(function(layer) {
    layer.fire('mouseout', {
      latlng: latlngPoint
    });
  });
  var results = leafletPip.pointInLayer(latlngPoint, geojson);
  results.forEach(function(layer) {
    layer.fire('mouseover', {
      latlng: latlngPoint
    });
  });
});

Here's the revisited Choropleth tutorial on Leaflet playground: http://playground-leaflet.rhcloud.com/sami/edit?html,output

Related Question