From bd6a65c00bd95f067929cc84a71d268b3f81adec Mon Sep 17 00:00:00 2001 From: Nano Miratus Date: Sun, 21 Jul 2024 08:15:05 +0200 Subject: [PATCH] fix randomPolygon generating polygons outside of the given `bbox` --- packages/turf-random/index.ts | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/packages/turf-random/index.ts b/packages/turf-random/index.ts index 47aa64db04..257e26c0f4 100644 --- a/packages/turf-random/index.ts +++ b/packages/turf-random/index.ts @@ -108,10 +108,14 @@ function randomPolygon( } = {} ): FeatureCollection { checkBBox(options.bbox); + // Default param if (count === undefined || count === null) { count = 1; } + if (options.bbox === undefined || options.bbox === null) { + options.bbox = [-180, -90, 180, 90]; + } if (!isNumber(options.num_vertices) || options.num_vertices === undefined) { options.num_vertices = 10; } @@ -122,6 +126,23 @@ function randomPolygon( options.max_radial_length = 10; } + const bboxWidth = Math.abs(options.bbox[0] - options.bbox[2]); + const bboxHeight = Math.abs(options.bbox[1] - options.bbox[3]); + + const maxRadius = Math.min(bboxWidth / 2, bboxHeight / 2); + + if (options.max_radial_length > maxRadius) { + throw new Error("max_radial_length is greater than the radius of the bbox"); + } + + // Create a padded bbox to avoid the polygons to be too close to the border + const paddedBbox = [ + options.bbox[0] + options.max_radial_length, + options.bbox[1] + options.max_radial_length, + options.bbox[2] - options.max_radial_length, + options.bbox[3] - options.max_radial_length, + ] as BBox; + const features = []; for (let i = 0; i < count; i++) { let vertices: any[] = []; @@ -145,7 +166,7 @@ function randomPolygon( // center the polygon around something vertices = vertices.map( - vertexToCoordinate(randomPositionUnchecked(options.bbox)) + vertexToCoordinate(randomPositionUnchecked(paddedBbox)) ); features.push(polygon([vertices])); }