Skip to content

Commit

Permalink
Added new point-to-polygon-distance package (#2735)
Browse files Browse the repository at this point in the history
Added turf-point-to-polygon-distance package to complement point-to-line functionality. Resolves #1743

---------

Co-authored-by: James Beard <[email protected]>
  • Loading branch information
pachacamac and smallsaucepan authored Nov 14, 2024
1 parent 1dec2f2 commit 5d1e0ec
Show file tree
Hide file tree
Showing 14 changed files with 690 additions and 2 deletions.
1 change: 1 addition & 0 deletions documentation.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ toc:
- pointOnFeature
- polygonTangents
- pointToLineDistance
- pointToPolygonDistance
- rhumbBearing
- rhumbDestination
- rhumbDistance
Expand Down
20 changes: 20 additions & 0 deletions packages/turf-point-to-polygon-distance/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
The MIT License (MIT)

Copyright (c) 2017 TurfJS

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
61 changes: 61 additions & 0 deletions packages/turf-point-to-polygon-distance/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# @turf/point-to-polygon-distance

<!-- Generated by documentation.js. Update this documentation by updating the source code. -->

## pointToPolygonDistance

Calculates the distance from a point to the edges of a polygon or multi-polygon.
Returns negative values for points inside the polygon.
Handles polygons with holes and multi-polygons.
A hole is treated as the exterior of the polygon.

### Parameters

* `point` **([Feature][1]<[Point][2]> | [Point][2] | [Position][3])** Input point
* `polygonOrMultiPolygon` **([Feature][1]<([Polygon][4] | [MultiPolygon][5])> | [Polygon][4] | [MultiPolygon][5])** Input polygon or multipolygon
* `options` **[Object][6]** Optional parameters (optional, default `{}`)

* `options.units` **Units** Units of the result e.g. "kilometers", "miles", "meters"
* `options.method` **(`"geodesic"` | `"planar"`)** Method of the result

<!---->

* Throws **[Error][7]** If input geometries are invalid

Returns **[number][8]** Distance in meters (negative values for points inside the polygon)

[1]: https://tools.ietf.org/html/rfc7946#section-3.2

[2]: https://tools.ietf.org/html/rfc7946#section-3.1.2

[3]: https://developer.mozilla.org/docs/Web/API/Position

[4]: https://tools.ietf.org/html/rfc7946#section-3.1.6

[5]: https://tools.ietf.org/html/rfc7946#section-3.1.7

[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object

[7]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error

[8]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number

<!-- This file is automatically generated. Please don't edit it directly. If you find an error, edit the source file of the module in question (likely index.js or index.ts), and re-run "yarn docs" from the root of the turf project. -->

---

This module is part of the [Turfjs project](https://turfjs.org/), an open source module collection dedicated to geographic algorithms. It is maintained in the [Turfjs/turf](https://github.com/Turfjs/turf) repository, where you can create PRs and issues.

### Installation

Install this single module individually:

```sh
$ npm install @turf/point-to-polygon-distance
```

Or install the all-encompassing @turf/turf module that includes all modules as functions:

```sh
$ npm install @turf/turf
```
65 changes: 65 additions & 0 deletions packages/turf-point-to-polygon-distance/bench.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { loadJsonFileSync } from "load-json-file";
import Benchmark from "benchmark";
import { pointToPolygonDistance } from "./index.js";
import { featureCollection } from "@turf/helpers";
import {
Feature,
GeoJsonProperties,
MultiPolygon,
Point,
Polygon,
} from "geojson";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const fixturesPath = path.join(__dirname, "test_fixtures") + path.sep;

const fixtures = fs.readdirSync(fixturesPath).map((filename) => {
return {
filename,
name: path.parse(filename).name,
geojson: loadJsonFileSync(fixturesPath + filename),
};
});

/**
* Benchmark Results
*
* long-lines-poly - pointA x 154,135 ops/sec ±0.36% (96 runs sampled)
* long-lines-poly - pointB x 167,645 ops/sec ±0.30% (98 runs sampled)
* long-lines-poly - pointC x 164,454 ops/sec ±0.25% (100 runs sampled)
* multi-polygon - outer x 16,604 ops/sec ±0.22% (97 runs sampled)
* multi-polygon - inner1 x 16,428 ops/sec ±0.20% (99 runs sampled)
* multi-polygon - inner2 x 16,329 ops/sec ±0.19% (100 runs sampled)
* multi-polygon - inner3-close-to-hole x 16,409 ops/sec ±0.26% (99 runs sampled)
* multi-polygon - in-hole-close-to-poly-in-hole x 16,589 ops/sec ±0.27% (101 runs sampled)
* multi-polygon - in-hole-close-to-hole-border x 16,251 ops/sec ±0.26% (98 runs sampled)
* multi-polygon - in-poly-in-hole x 16,763 ops/sec ±0.50% (98 runs sampled)
* simple-polygon - outer x 118,008 ops/sec ±0.17% (101 runs sampled)
* simple-polygon - inner x 121,173 ops/sec ±0.17% (99 runs sampled)
**/
const suite = new Benchmark.Suite("turf-point-to-polygon-distance");

for (const { name, geojson } of fixtures) {
// @ts-expect-error geojson
const fc = featureCollection(geojson?.features || []);
const points = fc.features.filter(
(f): f is Feature<Point, GeoJsonProperties> => f.geometry.type === "Point"
);
const polygon = fc.features.find((f) =>
["Polygon", "MultiPolygon"].includes(f.geometry.type)
) as Feature<Polygon | MultiPolygon, GeoJsonProperties>;
if (!polygon) {
throw new Error(`No polygon found in the feature collection in ${name}`);
}
for (const point of points) {
const caseName = `${name} - ${point.properties?.name || "unnamed point"}`;
suite.add(caseName, () => {
pointToPolygonDistance(point, polygon);
});
}
}
// @ts-expect-error benchmark
suite.on("cycle", (e) => console.log(String(e.target))).run();
90 changes: 90 additions & 0 deletions packages/turf-point-to-polygon-distance/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { booleanPointInPolygon } from "@turf/boolean-point-in-polygon";
import {
Feature,
Point,
Polygon,
MultiPolygon,
LineString,
Position,
} from "geojson";
import { pointToLineDistance } from "@turf/point-to-line-distance";
import { polygonToLine } from "@turf/polygon-to-line";
import { getGeom } from "@turf/invariant";
import { flattenEach } from "@turf/meta";
import { polygon, Units } from "@turf/helpers";

/**
* Calculates the distance from a point to the edges of a polygon or multi-polygon.
* Returns negative values for points inside the polygon.
* Handles polygons with holes and multi-polygons.
* A hole is treated as the exterior of the polygon.
*
* @param {Feature<Point> | Point | Position} point Input point
* @param {Feature<Polygon | MultiPolygon> | Polygon | MultiPolygon} polygonOrMultiPolygon Input polygon or multipolygon
* @param {Object} options Optional parameters
* @param {Units} options.units Units of the result e.g. "kilometers", "miles", "meters"
* @param {"geodesic" | "planar"} options.method Method of the result
* @returns {number} Distance in meters (negative values for points inside the polygon)
* @throws {Error} If input geometries are invalid
*/
export function pointToPolygonDistance(
point: Feature<Point> | Point | Position,
polygonOrMultiPolygon:
| Feature<Polygon | MultiPolygon>
| Polygon
| MultiPolygon,
options: {
units?: Units;
method?: "geodesic" | "planar";
} = {}
): number {
const method = options.method ?? "geodesic";
const units = options.units ?? "kilometers";
// Input validation
if (!point) throw new Error("point is required");
if (!polygonOrMultiPolygon)
throw new Error("polygon or multi-polygon is required");

const geom = getGeom(polygonOrMultiPolygon);

if (geom.type === "MultiPolygon") {
const distances = geom.coordinates.map((coords) =>
pointToPolygonDistance(point, polygon(coords), { method, units })
);
return (
Math.min(...distances.map(Math.abs)) *
(booleanPointInPolygon(point, polygonOrMultiPolygon) ? -1 : 1)
);
}

if (geom.coordinates.length > 1) {
// Has holes
const [exteriorDistance, ...interiorDistances] = geom.coordinates.map(
(coords) =>
pointToPolygonDistance(point, polygon([coords]), { method, units })
);
if (exteriorDistance >= 0) return exteriorDistance;
// point is inside the exterior polygon shape
const smallestInteriorDistance = Math.min(...interiorDistances);
// point is inside one of the holes?
if (smallestInteriorDistance < 0) return Math.abs(smallestInteriorDistance);
// find which is closer, the distance to the hole or the distance to the edge of the exterior
return Math.min(smallestInteriorDistance, Math.abs(exteriorDistance));
}
// The actual distance operation - on a normal, hole-less polygon in meters
const lines = polygonToLine(geom);
let minDistance = Infinity;
flattenEach(lines, (feature) => {
minDistance = Math.min(
minDistance,
pointToLineDistance(point, feature as Feature<LineString>, {
method,
units,
})
);
});

return booleanPointInPolygon(point, geom) ? -minDistance : minDistance;
}

export default pointToPolygonDistance;
79 changes: 79 additions & 0 deletions packages/turf-point-to-polygon-distance/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
{
"name": "@turf/point-to-polygon-distance",
"version": "7.1.0",
"description": "turf point-to-polygon-distance module",
"author": "Turf Authors",
"contributors": [
"Marc <@pachacamac>"
],
"license": "MIT",
"bugs": {
"url": "https://github.com/Turfjs/turf/issues"
},
"homepage": "https://github.com/Turfjs/turf",
"repository": {
"type": "git",
"url": "git://github.com/Turfjs/turf.git"
},
"funding": "https://opencollective.com/turf",
"publishConfig": {
"access": "public"
},
"keywords": [
"turf",
"gis",
"point",
"polygon",
"distance"
],
"type": "module",
"main": "dist/cjs/index.cjs",
"module": "dist/esm/index.js",
"types": "dist/esm/index.d.ts",
"exports": {
"./package.json": "./package.json",
".": {
"import": {
"types": "./dist/esm/index.d.ts",
"default": "./dist/esm/index.js"
},
"require": {
"types": "./dist/cjs/index.d.cts",
"default": "./dist/cjs/index.cjs"
}
}
},
"sideEffects": false,
"files": [
"dist"
],
"scripts": {
"bench": "tsx bench.ts",
"build": "tsup --config ../../tsup.config.ts",
"docs": "tsx ../../scripts/generate-readmes.ts",
"test": "npm-run-all --npm-path npm test:*",
"test:tape": "tsx test.ts"
},
"devDependencies": {
"@types/benchmark": "^2.1.5",
"@types/tape": "^4.2.32",
"benchmark": "^2.1.4",
"load-json-file": "^7.0.1",
"npm-run-all": "^4.1.5",
"tape": "^5.7.2",
"tsup": "^8.0.1",
"tsx": "^4.6.2",
"typescript": "^5.5.4",
"write-json-file": "^5.0.0"
},
"dependencies": {
"@turf/boolean-point-in-polygon": "workspace:^",
"@turf/helpers": "workspace:^",
"@turf/invariant": "workspace:^",
"@turf/meta": "workspace:^",
"@turf/point-to-line-distance": "workspace:^",
"@turf/polygon-to-line": "workspace:^",
"@types/geojson": "^7946.0.10",
"tslib": "^2.6.2"
}
}
62 changes: 62 additions & 0 deletions packages/turf-point-to-polygon-distance/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import fs from "fs";
import test from "tape";
import path from "path";
import { fileURLToPath } from "url";
import { loadJsonFileSync } from "load-json-file";
import { point } from "@turf/helpers";
import { polygon } from "@turf/helpers";
import { pointToPolygonDistance } from "./index.js";
import { featureCollection } from "@turf/helpers";
import {
Feature,
GeoJsonProperties,
MultiPolygon,
Point,
Polygon,
} from "geojson";

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const fixturesPath = path.join(__dirname, "test_fixtures") + path.sep;

const fixtures = fs.readdirSync(fixturesPath).map((filename) => {
return {
filename,
name: path.parse(filename).name,
geojson: loadJsonFileSync(fixturesPath + filename),
};
});

test("turf-point-to-polygon-distance", (t) => {
for (const { name, geojson } of fixtures) {
// @ts-expect-error geojson
const fc = featureCollection(geojson?.features || []);
const points: Feature<Point, GeoJsonProperties>[] = fc.features.filter(
(f): f is Feature<Point, GeoJsonProperties> => f.geometry.type === "Point"
);
const polygon = fc.features.find((f) =>
["Polygon", "MultiPolygon"].includes(f.geometry.type)
) as Feature<Polygon | MultiPolygon, GeoJsonProperties>;
if (!polygon)
throw new Error(`No polygon found in the feature collection in ${name}`);
for (const point of points) {
const expectedDistance = point.properties?.expected_distance;
const units = point.properties?.units;
const distance = pointToPolygonDistance(point, polygon, { units });
t.equal(distance, expectedDistance, name, {
message: `${name} - ${point.properties?.name}`,
});
}
}
// Handle Errors
t.throws(
// @ts-expect-error invalid geometry
() => pointToPolygonDistance(polygon([]), polygon([])),
"throws - invalid geometry"
);
t.throws(
() => pointToPolygonDistance(point([0, 0]), polygon([])),
"throws - empty coordinates"
);
t.end();
});
Loading

0 comments on commit 5d1e0ec

Please sign in to comment.