Skip to content

Instantly share code, notes, and snippets.

@reyemtm
Created December 16, 2023 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reyemtm/663f207c67c8e46e695b0251efb4f2d0 to your computer and use it in GitHub Desktop.
Save reyemtm/663f207c67c8e46e695b0251efb4f2d0 to your computer and use it in GitHub Desktop.
Find the perpendicular line from a line AB to point C using Turf JS
function slopeIx(a, b, c) {
//GET POINT OF X AND Y INTERCEPT FROM POINT C AND LINE AB
const lines = turf.featureCollection([]);
const bearing1 = turf.bearing(a, b);
const slope = (b[1] - a[1]) / (b[0] - a[0]);
const point1 = [c[0], slope * (c[0] - a[0]) + a[1]];
const point2 = [(c[1] - a[1]) / slope + a[0], c[1]];
const lineArray = [a, b, point1, point2];
//NORMALIZE LINE
lineArray.sort((a, b) => b[0] - a[0]);
lines.features.push(turf.lineString(lineArray));
//CREATE 90DEG LINE FROM POINT C TO LINE AB
const { geometry: p90 } = turf.destination(
turf.point(c),
//THE DISTANCE A TO C WILL ALWAYS BE LARGER THAN THE DISTANCE FROM C TO THE EXTENDED LINE AB
turf.distance(a, c),
bearing1 + 90
);
const { geometry: p91 } = turf.destination(
turf.point(c),
turf.distance(a, c),
bearing1 - 90
);
const pline = turf.lineString([p90.coordinates, p91.coordinates]);
lines.features.push(pline);
//GET INTERSECTING POINT 90DEG FROM POINT C TO EXTENDED LINE AB
const intersectingPoint = turf.lineIntersect(
lines.features[0],
lines.features[1]
);
//GET THE DISTANCE FROM THE INTERSECTING POINT TO POINT C
const distance = turf.distance(intersectingPoint.features[0], turf.point(c), {
units: "miles"
});
return { distance, intersectingPoint, lines }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment