Skip to content

Commit

Permalink
Ported turf measurement center function
Browse files Browse the repository at this point in the history
  • Loading branch information
P72B committed Sep 27, 2023
1 parent 45004eb commit 8339af2
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ fun bbox(geometry: MultiPolygon) = computeBbox(geometry.coordAll())
* @return A [BoundingBox] that covers the geometry.
*/
@ExperimentalTurfApi
fun bbox(feature: Feature): BoundingBox? = computeBbox(feature.coordAll() ?: emptyList())
fun bbox(feature: Feature): BoundingBox = computeBbox(feature.coordAll() ?: emptyList())

/**
* Takes a feature collection and calculates a bbox that covers all features in the collection.
Expand Down Expand Up @@ -463,3 +463,18 @@ fun midpoint(point1: Position, point2: Position): Position {

return destination(point1, dist / 2, heading)
}

/**
* Takes any kind of [Feature] and returns the center point. It will create a [BoundingBox] around the given
* [Feature] and calculates the center point of it.
*
* @param feature the feature to find the center for
* @return A [Point] holding the center coordinates
*/
@ExperimentalTurfApi
fun center(feature: Feature): Point {
val ext = bbox(feature)
val x = (ext.southwest.longitude + ext.northeast.longitude) / 2
val y = (ext.southwest.latitude + ext.northeast.latitude) / 2
return Point(Position(longitude = x, latitude = y))
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
@file:Suppress("MagicNumber")

package io.github.dellisd.spatialk.turf

import io.github.dellisd.spatialk.geojson.BoundingBox
import io.github.dellisd.spatialk.geojson.LineString
import io.github.dellisd.spatialk.geojson.Feature
import io.github.dellisd.spatialk.geojson.Point
import io.github.dellisd.spatialk.geojson.Polygon
import io.github.dellisd.spatialk.geojson.Position
Expand Down Expand Up @@ -121,4 +121,14 @@ class TurfMeasurementTest {
assertDoubleEquals(-76.6311, midpoint.longitude, 0.0001)
assertDoubleEquals(42.2101, midpoint.latitude, 0.0001)
}

@Test
fun testCenter() {
val geometry = Polygon.fromJson(readResource("measurement/area/other.json"))

val centerPoint = center(Feature(geometry))

assertDoubleEquals(-75.71805238723755, centerPoint.coordinates.longitude, 0.0001)
assertDoubleEquals(45.3811030151199, centerPoint.coordinates.latitude, 0.0001)
}
}

0 comments on commit 8339af2

Please # to comment.