Last active
April 28, 2020 12:19
-
-
Save martinhoeller/b93080980e181a79c642d035d128680e to your computer and use it in GitHub Desktop.
A bounding box implementation that can be initialized either with NE/SE or with an array of coordinates.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import CoreLocation | |
/** | |
A bounding box implementation that can be initialized either with NE/SE or with an array of coordinates. | |
*/ | |
struct BoundingBox { | |
let ne: CLLocationCoordinate2D | |
let sw: CLLocationCoordinate2D | |
let center: CLLocationCoordinate2D | |
let latitudeSpread: CLLocationDegrees | |
let longitudeSpread: CLLocationDegrees | |
init(ne: CLLocationCoordinate2D, sw: CLLocationCoordinate2D) { | |
self.ne = ne | |
self.sw = sw | |
latitudeSpread = ne.latitude - sw.latitude | |
longitudeSpread = ne.longitude - sw.longitude | |
center = CLLocationCoordinate2D(latitude: sw.latitude + latitudeSpread / 2, | |
longitude: sw.longitude + longitudeSpread / 2) | |
} | |
init(coordinates: [CLLocationCoordinate2D]) { | |
if coordinates.count == 0 { | |
self.init(ne: CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0), | |
sw: CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0)) | |
return | |
} | |
if coordinates.count == 1 { | |
self.init(ne: coordinates[0], sw: coordinates[0]) | |
return | |
} | |
var ne = CLLocationCoordinate2D(latitude: -.infinity, longitude: -.infinity) | |
var sw = CLLocationCoordinate2D(latitude: .infinity, longitude: .infinity) | |
for coordinate in coordinates { | |
ne.latitude = max(ne.latitude, coordinate.latitude) | |
ne.longitude = max(ne.longitude, coordinate.longitude) | |
sw.latitude = min(sw.latitude, coordinate.latitude) | |
sw.longitude = min(sw.longitude, coordinate.longitude) | |
} | |
self.init(ne: ne, sw: sw) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment