I'm displaying some polygons in Leaflet, and using Turf JS to do some calculating.
After drawing a line between the centroids of two neighboring polygons, I want to find the intersection of the line with the boundary of one of the polygons.
My code looks something like this:
// Calculate the distance beteween centroid of highlighted polygon and the centroid of the neighboring polygon.
const highlight_centroid = turf.centerOfMass(highlight_feature);
const centroid = turf.centerOfMass(neighbor_feature);
const line = turf.lineString([highlight_centroid, centroid]);
// Draw line between the centroids
const leaflet_line = L.polyline([turfToLeaflet(highlight_centroid), turfToLeaflet(centroid)]).addTo(test_layer);
// Find the intersection of this line with the boundary of neighor_feature
// First, check if it intersects. Turf says TRUE, the line DOES intersect neighbor_feature
console.log(turf.booleanIntersects(line,neighbor_feature));
// But lineIntersect() returns an empty feature collection.
// There should be a point coordinate
const intersection = turf.lineIntersect(line,neighbor_feature);
console.log(intersection);
(There's a functioning CodePen here: https://codepen.io/Kirkman/pen/JjOxjwP)
Turf's booleanIntersects()
method says TRUE
, they do intersect.
But when I try to use lineIntersect()
, Turf just returns an empty feature collection. The same occurs if I try other similar methods like lineOverlap()
or lineSplit()
.
Am I doing something wrong? I cannot figure out why these methods are not returning anything. The line obviously intersects the polys.
Best Answer
Your problems comes from the fact that
turf.centerOfMass
method returns point object. When you create line withturf.lineString
method, specifying line coordinates with point objects, this obviously produces valid GeoJSON line, but for some reasonturf.lineIntersect
method does not interpret it correctly when doing intersection.Solution is simply to feed bare coordinates to
turf.lineString
, so line creating code should look like this: