以给定坐标和距离(米)计算新坐标

时间:2015-10-05 11:23:08

标签: ios swift core-location cllocationdistance cllocationcoordinate2d

我有一个坐标和一个CoreData数据库,其中包含具有纬度和经度值的条目。我想找到给定方形区域内的所有对象,因此想知道左上角和右下角点与我的点的距离。

代码:

let coordinate = CLLocationCoordinate2D(latitude: 9.0, longitude: 50.0)
let distance: CLLocationDistance = 5000 // 5km
let topLeftCoordinate = ... // how to calculate this?
let bottomRightCoordinate = ... // and that?

1 个答案:

答案 0 :(得分:2)

一种方法是定义辅助方法,以便使用MapKit和CoreLoation给出基于给定距离(以米为单位)的坐标来计算新坐标,如下所示:

// 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)
}

然后上面的代码看起来就像这样:

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)

希望在遇到这个时帮助那些人。

谨慎信息:如果有人认为(似乎有很多人认为)自我回答的问题不合适,请先阅读this