MKCoordinateRegionMakeWithDistance 的反函数?

Reverse function of MKCoordinateRegionMakeWithDistance?

MapKit 的内置函数 MKCoordinateRegionMakeWithDistance 获取以米为单位的距离并将它们转换为 MKCoordinateRegion:

func MKCoordinateRegionMakeWithDistance(
    _ centerCoordinate: CLLocationCoordinate2D, 
    _ latitudinalMeters: CLLocationDistance, 
    _ longitudinalMeters: CLLocationDistance) 
        -> MKCoordinateRegion

是否有一个反向函数接受 MKCoordinateRegion 并给我纬度和纵向米?

MKCoordinateRegion 给出一个中心(纬度和经度)和跨度(delta 纬度和经度)。给定这些值,您可以确定区域边缘的纬度和经度位置。一旦这样做,您就可以使用半正弦公式来获得纬度和经度距离,并且您已经知道了中心。事实上,CLLocation 有一个函数 distanceFromLocation:(const CLLocation *)location,您应该使用它来避免直接执行公式。

基于 Adam H.s 的想法,这是我在 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)
}

测试设计:

  • 对纬度和经度使用不同的数字来查找变量混淆的错误
  • 四舍五入检查约 5 位有效小数位