1

I have a coordinate and a CoreData database with entries which have latitude and longitude values. I want to find all objects within a given square region and therefore would like to know the top-left and bottom-right corner points with a distance to my point.

Code:

let coordinate = CLLocationCoordinate2D(latitude: 9.0, longitude: 50.0)
let distance: CLLocationDistance = 5000 // 5km
let topLeftCoordinate = ... // how to calculate this?
let bottomRightCoordinate = ... // and that?
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Jeehut
  • 20,202
  • 8
  • 59
  • 80

1 Answers1

5

One way would be to define helper methods that make it easy to calculate new coordinates based on a coordinate given a distance in meters using the MapKit and CoreLoation like so:

// Create new coordinate with equal latitude and longitude distances (distance can be both positive and negative).
func coordinate(from coordinate: CLLocationCoordinate2D, distance: CLLocationDistance) -> CLLocationCoordinate2D {
    return self.coordinate(from: coordinate, latitudeDistance: distance, longitudeDistance: distance)
}

// Create new coordinate with latitude and longitude distances (distances can be both positive and negative).
func coordinate(from coordinate: CLLocationCoordinate2D, latitudeDistance: CLLocationDistance, longitudeDistance: CLLocationDistance) -> CLLocationCoordinate2D {
    let region = MKCoordinateRegionMakeWithDistance(coordinate, latitudeDistance, longitudeDistance)

    let newLatitude = coordinate.latitude + region.span.latitudeDelta
    let newLongitude = coordinate.longitude + region.span.longitudeDelta

    return CLLocationCoordinate2D(latitude: newLatitude, longitude: newLongitude)
}

Then the above code would simply look like this:

let coordinate = CLLocationCoordinate2D(latitude: 9.0, longitude: 50.0)
let distance: CLLocationDistance = 5000 // 5km
let topLeftCoordinate = self.coordinate(from: coordinate, distance: -distance)
let bottomRightCoordinate = self.coordinate(from: coordinate, distance: distance)

Hope it helps someone out there when coming across this.


Precautious Info: Just in case someone thinks (as many seem to do) that a self-answered question isn't appropriate on SO, please read this first.

Community
  • 1
  • 1
Jeehut
  • 20,202
  • 8
  • 59
  • 80