MapKit的内置函数MKCoordinateRegionMakeWithDistance
以米为单位将距离转换为MKCoordinateRegion
:
func MKCoordinateRegionMakeWithDistance(
_ centerCoordinate: CLLocationCoordinate2D,
_ latitudinalMeters: CLLocationDistance,
_ longitudinalMeters: CLLocationDistance)
-> MKCoordinateRegion
是否有一个倒数函数需要MKCoordinateRegion
并给我纬度和经度?
答案 0 :(得分:4)
MKCoordinateRegion
给出中心(纬度和经度)和跨度(delta纬度和经度)。给定这些值,您可以确定纬度和经度区域边缘的位置。完成此操作后,您可以使用Haversine公式获取纬向和纵向距离,并且您已经知道中心。实际上,CLLocation
具有函数distanceFromLocation:(const CLLocation *)location
,应使用该函数来避免直接实现公式。
答案 1 :(得分:1)
基于Adam H.的想法,这是我在Swift 4
中使用单元测试的实现:
extension MKCoordinateRegion {
/// middle of the south edge
var south: CLLocation {
return CLLocation(latitude: center.latitude - span.latitudeDelta / 2, longitude: center.longitude)
}
/// middle of the north edge
var north: CLLocation {
return CLLocation(latitude: center.latitude + span.latitudeDelta / 2, longitude: center.longitude)
}
/// middle of the east edge
var east: CLLocation {
return CLLocation(latitude: center.latitude, longitude: center.longitude + span.longitudeDelta / 2)
}
/// middle of the west edge
var west: CLLocation {
return CLLocation(latitude: center.latitude, longitude: center.longitude - span.longitudeDelta / 2)
}
/// distance between south and north in meters. Reverse function for MKCoordinateRegionMakeWithDistance
var latitudinalMeters: CLLocationDistance {
return south.distance(from: north)
}
/// distance between east and west in meters. Reverse function for MKCoordinateRegionMakeWithDistance
var longitudinalMeters: CLLocationDistance {
return east.distance(from: west)
}
}
单元测试:
func testMKCoordinateRegionMakeWithDistance() {
// arbitrary parameters
let center = CLLocationCoordinate2DMake(49, 9)
let latitudinalMeters: CLLocationDistance = 1000
let longitudinalMeters: CLLocationDistance = 2000
let region = MKCoordinateRegionMakeWithDistance(center, latitudinalMeters, longitudinalMeters)
XCTAssertEqual(latitudinalMeters, round(region.latitudinalMeters*100)/100)
XCTAssertEqual(longitudinalMeters, round(region.longitudinalMeters*100)/100)
}
测试设计: