gpt4 book ai didi

ios - 使用给定的坐标和以米为单位的距离计算新坐标

转载 作者:行者123 更新时间:2023-11-28 11:14:09 24 4
gpt4 key购买 nike

我有一个坐标和一个 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?

最佳答案

一种方法是定义辅助方法,这样可以使用 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)

希望它能帮助遇到此问题的人。


注意事项: 以防万一有人认为(很多人似乎都这么认为) self 回答的问题不适合 SO,请阅读 this首先。

关于ios - 使用给定的坐标和以米为单位的距离计算新坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32947378/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com