3

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

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

是否有一个反向函数需要一个MKCoordinateRegion并给我latitudinalMeters和longitudinalMeters?

4

2 回答 2

4

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

于 2018-08-10T14:29:20.250 回答
1

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

测试设计:

  • 对 lat 和 long 使用不同的数字来查找变量混合的错误
  • 四舍五入检查约 5 个有效小数位
于 2018-08-10T14:59:16.713 回答