2

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.

  • 1
    Have you read this tutorial? – Antonio Falciano Jun 21 '17 at 17:28
  • you mean that i should use onEachFeature() to check if map.getCenter() is lying within the respective feature? but I don't understand how to check for each feature instead of for the whole geojson – Revo Jun 22 '17 at 5:57
  • No, but onEachFeature() should indicate a way! If you don't want to click or mouseover on each feature, you could emulate the user actions. See the answer below. – Antonio Falciano Jun 23 '17 at 9:24
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.