Skip to content

Instantly share code, notes, and snippets.

@mmuszynski
Last active June 21, 2016 23:46
Show Gist options
  • Save mmuszynski/760c7e3e6b886eec71bbe05d8189e5a4 to your computer and use it in GitHub Desktop.
Save mmuszynski/760c7e3e6b886eec71bbe05d8189e5a4 to your computer and use it in GitHub Desktop.
protocol Landmarkable {
var coordinate: CLLocation? { get } //classes must provide at least a Read-Only location called "coordinate"
func distanceFrom(location: CLLocation) -> CLLocationDistance //classes must provide a distance from another location
}
protocol Outlineable: Landmarkable {
var outline: [CLLocation]? { get } //must provide an outline represented by an array of locations
var center: CLLocation? { get } //must provide a center location
}
extension Landmarkable {
//this is a default implementation for all Landmarkable objects
//calculates the distance from an arbitrary location to the landmark
//if it can't be done, returns the maximum distance
final func distanceFrom(location: CLLocation) -> CLLocationDistance {
if let co = self.coordinate {
return co.distanceFromLocation(location)
}
return CLLocationDistanceMax
}
}
extension Outlineable {
//provides an unweighted average of the location array
//returns nil if unable to get location array or if that array has no locations in it
var center: CLLocation? {
if let locations = self.outline where locations.count > 0 {
let total = locations.reduce((x: 0.0, y: 0.0, z: 0.0), combine: { (totals, nextLocation) -> (Double, Double, Double) in
return (totals.x + nextLocation.coordinate.latitude,
totals.y + nextLocation.coordinate.longitude,
totals.z + nextLocation.altitude)
})
let count = Double(locations.count)
let coordinate = CLLocationCoordinate2D(latitude: total.x / count, longitude: total.y / count)
let altitude = total.z / count
let computedCenter = CLLocation(coordinate: coordinate, altitude: altitude, horizontalAccuracy: kCLLocationAccuracyBest, verticalAccuracy: kCLLocationAccuracyBest, timestamp: NSDate())
return computedCenter
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment