diff --git a/packages/turf-clusters-dbscan/index.ts b/packages/turf-clusters-dbscan/index.ts index 66ac01d75..404b54ab1 100644 --- a/packages/turf-clusters-dbscan/index.ts +++ b/packages/turf-clusters-dbscan/index.ts @@ -3,6 +3,7 @@ import { clone } from "@turf/clone"; import { Units } from "@turf/helpers"; import KDBush from "kdbush"; import * as geokdbush from "geokdbush"; +import { convertLength } from "@turf/helpers"; /** * Point classification within the cluster. @@ -88,6 +89,12 @@ function clustersDbscan( } kdIndex.finish(); + const maxDistanceKm = convertLength( + maxDistance, + options.units || "kilometers", + "kilometers" + ); + // Keeps track of whether a point has been visited or not. var visited = points.features.map((_) => false); @@ -108,7 +115,7 @@ function clustersDbscan( return ( geokdbush // @ts-expect-error 2345 until https://github.com/mourner/geokdbush/issues/20 is resolved - .around(kdIndex, x, y, undefined, maxDistance) + .around(kdIndex, x, y, undefined, maxDistanceKm) .map((id) => ({ minX: points.features[id].geometry.coordinates[0], minY: points.features[id].geometry.coordinates[1], diff --git a/packages/turf-clusters-dbscan/test.ts b/packages/turf-clusters-dbscan/test.ts index cabcd6645..884cf8f21 100644 --- a/packages/turf-clusters-dbscan/test.ts +++ b/packages/turf-clusters-dbscan/test.ts @@ -154,3 +154,38 @@ test("clusters-dbscan -- allow input mutation", (t) => { t.equal(oldPoints.features[1].properties.cluster, 1, "cluster is 1"); t.end(); }); + +test("clusters-dbscan -- respect units option", (t) => { + const testPoints = featureCollection([ + point([0, 0]), + point([0.000001, 0]), + point([0.001, 0]), + point([0.8, 0]), + ]); + + const kmPoints = clustersDbscan(testPoints, 1, { minPoints: 1 }); + const mPoints = clustersDbscan(testPoints, 1, { + minPoints: 1, + units: "meters", + }); + const degreePoints = clustersDbscan(testPoints, 1, { + minPoints: 1, + units: "degrees", + }); + + const kmClusters = new Set( + kmPoints.features.map((f) => f.properties.cluster) + ); + + const mClusters = new Set(mPoints.features.map((f) => f.properties.cluster)); + + const degreeClusters = new Set( + degreePoints.features.map((f) => f.properties.cluster) + ); + + t.equal(kmClusters.size, 2); + t.equal(mClusters.size, 3); + t.equal(degreeClusters.size, 1); + + t.end(); +});