Leaflet – Getting Attributes of Overlapping Polygons Using Turf.js

geojsongeometryjavascriptleafletturf

I have a Leaflet Polyline:

var polyline = L.Polyline(polylineData).addTo(map);

and a Leaflet GeoJSON of Polygons:

var countries = L.geoJson(countries, {style:{color:'darkgrey', opacity:1,fillColor:'lightgrey', fillOpacity:0.7, weight:2}}).addTo(map);

They look like this on the map:

enter image description here

Imagine that the Polyline represents a driving route that goes across Europe. The GeoJSON is a collection of National Boundaries with associated attribute information. I need to know what countries the driving route goes through. For example, In the case of this line I need to know that it is passing through the United Kingdom, France and Switzerland. The GeoJSON contains the associated country names as properties in each feature.

I am hoping that a function within the Turf.js library is suitable though am not sure which one?

Best Answer

You can use countries.eachLayer group layer method to iterate through layer features and then use turf.booleanIntersects method to check which country feature intersects polyline.

To log intersected countries on the console, code could then look something like this (assuming feature property name contains country name):

var polyline = L.Polyline(polylineData).addTo(map);
var polylineFeature = polyLine.toGeoJSON();

countries.eachLayer(function(layer) {
  if (turf.booleanIntersects(layer.feature, polylineFeature)) {
    console.log(layer.feature.properties.name);
  }
});