index.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // index.ts
  2. import {
  3. convertLength,
  4. feature,
  5. lineString,
  6. point
  7. } from "@turf/helpers";
  8. import { nearestPointOnLine } from "@turf/nearest-point-on-line";
  9. import { featureOf } from "@turf/invariant";
  10. import { segmentEach } from "@turf/meta";
  11. import { rhumbDistance } from "@turf/rhumb-distance";
  12. function pointToLineDistance(pt, line, options = {}) {
  13. var _a, _b;
  14. const method = (_a = options.method) != null ? _a : "geodesic";
  15. const units = (_b = options.units) != null ? _b : "kilometers";
  16. if (!pt) {
  17. throw new Error("pt is required");
  18. }
  19. if (Array.isArray(pt)) {
  20. pt = point(pt);
  21. } else if (pt.type === "Point") {
  22. pt = feature(pt);
  23. } else {
  24. featureOf(pt, "Point", "point");
  25. }
  26. if (!line) {
  27. throw new Error("line is required");
  28. }
  29. if (Array.isArray(line)) {
  30. line = lineString(line);
  31. } else if (line.type === "LineString") {
  32. line = feature(line);
  33. } else {
  34. featureOf(line, "LineString", "line");
  35. }
  36. let distance = Infinity;
  37. const p = pt.geometry.coordinates;
  38. segmentEach(line, (segment) => {
  39. if (segment) {
  40. const a = segment.geometry.coordinates[0];
  41. const b = segment.geometry.coordinates[1];
  42. const d = distanceToSegment(p, a, b, { method });
  43. if (d < distance) {
  44. distance = d;
  45. }
  46. }
  47. });
  48. return convertLength(distance, "degrees", units);
  49. }
  50. function distanceToSegment(p, a, b, options) {
  51. if (options.method === "geodesic") {
  52. const nearest = nearestPointOnLine(lineString([a, b]).geometry, p, {
  53. units: "degrees"
  54. });
  55. return nearest.properties.dist;
  56. }
  57. const v = [b[0] - a[0], b[1] - a[1]];
  58. const w = [p[0] - a[0], p[1] - a[1]];
  59. const c1 = dot(w, v);
  60. if (c1 <= 0) {
  61. return rhumbDistance(p, a, { units: "degrees" });
  62. }
  63. const c2 = dot(v, v);
  64. if (c2 <= c1) {
  65. return rhumbDistance(p, b, { units: "degrees" });
  66. }
  67. const b2 = c1 / c2;
  68. const Pb = [a[0] + b2 * v[0], a[1] + b2 * v[1]];
  69. return rhumbDistance(p, Pb, { units: "degrees" });
  70. }
  71. function dot(u, v) {
  72. return u[0] * v[0] + u[1] * v[1];
  73. }
  74. var turf_point_to_line_distance_default = pointToLineDistance;
  75. export {
  76. turf_point_to_line_distance_default as default,
  77. pointToLineDistance
  78. };
  79. //# sourceMappingURL=index.js.map