diff --git a/Sources/GeoJSONKitTurf/ClosestCoordinate.swift b/Sources/GeoJSONKitTurf/ClosestCoordinate.swift index 3136c6a..481e6a9 100644 --- a/Sources/GeoJSONKitTurf/ClosestCoordinate.swift +++ b/Sources/GeoJSONKitTurf/ClosestCoordinate.swift @@ -17,9 +17,11 @@ extension GeoJSON.LineString { public struct IndexedCoordinate { /// The coordinate public let coordinate: Array.Element + /// The index of the coordinate public let index: Array.Index - /// The coordinate’s distance from the start of the polyline + + /// The coordinate’s distance along the polyline from the start of the polyline public let distance: GeoJSON.Distance } @@ -36,37 +38,47 @@ extension GeoJSON.LineString.IndexedCoordinate { } var closestCoordinate: GeoJSON.LineString.IndexedCoordinate? - var closestDistance: GeoJSON.Distance? + var closestDistance: GeoJSON.Distance = .greatestFiniteMagnitude + var cumulativeDistance: GeoJSON.Distance = 0 for index in 0.. GeoJSON.LineString? { // The method is porting from https://github.com/Turfjs/turf/blob/5375941072b90d489389db22b43bfe809d5e451e/packages/turf-line-slice-along/index.js - guard startDistance >= 0.0 && stopDistance >= startDistance else { return nil } + guard startDistance >= 0, stopDistance >= startDistance else { return nil } let positions = self.coordinates var traveled: GeoJSON.Distance = 0 var slice = [GeoJSON.Position]() for i in 0..= traveled && i == positions.endIndex - 1 { + if startDistance >= traveled, i == positions.endIndex - 1 { break - } else if traveled > startDistance && slice.isEmpty { + } else if traveled > startDistance, slice.isEmpty { let overshoot = startDistance - traveled if overshoot == 0.0 { slice.append(positions[i]) @@ -77,7 +77,9 @@ extension GeoJSON.LineString { traveled += positions[i].distance(to: positions[i + 1]) } - if traveled < startDistance { return nil } + if traveled < startDistance { + return nil + } if let last = positions.last { return GeoJSON.LineString(positions: [last, last])