79 lines
2.6 KiB
JavaScript
79 lines
2.6 KiB
JavaScript
import * as turf from "@turf/turf";
|
|
|
|
/**
|
|
* Converts an array of canvas-compatible points into a Turf.js Polygon.
|
|
*
|
|
* @param {{x: number, y: number}[]} points - Array of points with x and y properties.
|
|
*
|
|
* @returns {import('@turf/turf').Feature<import('@turf/turf').Polygon> | null} A Turf.js Polygon feature, or null if input is invalid.
|
|
*/
|
|
export function toTurfPolygon(points) {
|
|
if (!points || points.length < 3) {
|
|
console.error("Invalid input for polygon:", points);
|
|
return null;
|
|
}
|
|
|
|
const coords = points.map(p => [p.y, p.x]);
|
|
coords.push(coords[0]);
|
|
return turf.polygon([coords]);
|
|
}
|
|
|
|
/**
|
|
* Merges two polygons (in canvas format) into a single Turf.js polygon using turf.union.
|
|
*
|
|
* @param {{x: number, y: number}[]} polygonA - First polygon (array of points).
|
|
* @param {{x: number, y: number}[]} polygonB - Second polygon (array of points).
|
|
*
|
|
* @returns {import('@turf/turf').Feature<import('@turf/turf').Polygon> | null} A merged Turf.js polygon, or null on failure.
|
|
*/
|
|
export function mergeTurfPolygons(polygonA, polygonB) {
|
|
const turfPolygonA = toTurfPolygon(polygonA);
|
|
const turfPolygonB = toTurfPolygon(polygonB);
|
|
|
|
return turf.union(turf.featureCollection([turfPolygonA, turfPolygonB]));
|
|
}
|
|
|
|
/**
|
|
* Adds a new polygon to an existing merged Turf.js polygon.
|
|
*
|
|
* @param {import('@turf/turf').Feature<import('@turf/turf').Polygon>} polygonA - Existing merged Turf.js polygon.
|
|
* @param {{x: number, y: number}[]} polygonB - New polygon in canvas point format to add to the merge.
|
|
*
|
|
* @returns {import('@turf/turf').Feature<import('@turf/turf').Polygon>} Updated merged Turf.js polygon.
|
|
*/
|
|
export function addTurfPolygonToMerge(polygonA, polygonB) {
|
|
const testB = toTurfPolygon(polygonB);
|
|
return turf.union(turf.featureCollection([polygonA, testB]));
|
|
}
|
|
|
|
/**
|
|
* @param {{x: number, y: number}[][]} polygons
|
|
* @returns {Feature<Polygon | MultiPolygon, GeoJsonProperties>}
|
|
*/
|
|
|
|
export function mergePolygons(polygons) {
|
|
|
|
if (!polygons || polygons.length === 0)
|
|
return undefined;
|
|
|
|
if (polygons.length === 1)
|
|
return toTurfPolygon(polygons[0]);
|
|
|
|
return turf.union(turf.featureCollection(polygons.map(p => toTurfPolygon(p))));
|
|
}
|
|
|
|
/**
|
|
*
|
|
* @param {Array<Feature<Polygon | MultiPolygon, GeoJsonProperties>>|undefined} features
|
|
* @returns {Feature<Polygon | MultiPolygon, GeoJsonProperties>|undefined|*}
|
|
*/
|
|
export function mergePolygonFeatures(features) {
|
|
|
|
if (!features || features.length === 0)
|
|
return undefined;
|
|
|
|
if (features.length === 1)
|
|
return features[0];
|
|
|
|
return turf.union(turf.featureCollection(features));
|
|
} |