index.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // index.ts
  2. import { booleanPointInPolygon } from "@turf/boolean-point-in-polygon";
  3. import { pointToLineDistance } from "@turf/point-to-line-distance";
  4. import { polygonToLine } from "@turf/polygon-to-line";
  5. import { getGeom } from "@turf/invariant";
  6. import { flattenEach } from "@turf/meta";
  7. import { polygon } from "@turf/helpers";
  8. function pointToPolygonDistance(point, polygonOrMultiPolygon, options = {}) {
  9. var _a, _b;
  10. const method = (_a = options.method) != null ? _a : "geodesic";
  11. const units = (_b = options.units) != null ? _b : "kilometers";
  12. if (!point) throw new Error("point is required");
  13. if (!polygonOrMultiPolygon)
  14. throw new Error("polygon or multi-polygon is required");
  15. const geom = getGeom(polygonOrMultiPolygon);
  16. if (geom.type === "MultiPolygon") {
  17. const distances = geom.coordinates.map(
  18. (coords) => pointToPolygonDistance(point, polygon(coords), { method, units })
  19. );
  20. return Math.min(...distances.map(Math.abs)) * (booleanPointInPolygon(point, polygonOrMultiPolygon) ? -1 : 1);
  21. }
  22. if (geom.coordinates.length > 1) {
  23. const [exteriorDistance, ...interiorDistances] = geom.coordinates.map(
  24. (coords) => pointToPolygonDistance(point, polygon([coords]), { method, units })
  25. );
  26. if (exteriorDistance >= 0) return exteriorDistance;
  27. const smallestInteriorDistance = Math.min(...interiorDistances);
  28. if (smallestInteriorDistance < 0) return Math.abs(smallestInteriorDistance);
  29. return Math.min(smallestInteriorDistance, Math.abs(exteriorDistance));
  30. }
  31. const lines = polygonToLine(geom);
  32. let minDistance = Infinity;
  33. flattenEach(lines, (feature) => {
  34. minDistance = Math.min(
  35. minDistance,
  36. pointToLineDistance(point, feature, {
  37. method,
  38. units
  39. })
  40. );
  41. });
  42. return booleanPointInPolygon(point, geom) ? -minDistance : minDistance;
  43. }
  44. var turf_point_to_polygon_distance_default = pointToPolygonDistance;
  45. export {
  46. turf_point_to_polygon_distance_default as default,
  47. pointToPolygonDistance
  48. };
  49. //# sourceMappingURL=index.js.map