Convert MKCoordinateRegion to MKMapRect

前端 未结 10 693
南笙
南笙 2020-12-02 10:52

I have a square MKMapView in my app, and I wish to set a center point and the exact height/width of the view in meters.

Creating an MKCoordinateRegion and setting th

10条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 11:19

    The answer @David gave (and consequently the Swift 3 version by @onmyway133) has a significant error whenever the region crosses over the anti-meridian from the Eastern Hemisphere (longitude 0 degrees to 180 degrees) to the Western Hemisphere (longitude -180 degrees to 0 degrees). The width of the MKMapRect will be bigger than it should be (usually much bigger).

    Here is the fix (for the Swift 3 code):

    let topLeftMapPoint = MKMapPointForCoordinate(topLeft)
    let bottomRightMapPoint = MKMapPointForCoordinate(bottomRight)
    var width = bottomRightMapPoint.x - topLeftMapPoint.x
    if width < 0.0 {
        // Rect crosses from the Eastern Hemisphere to the Western Hemisphere
        width += MKMapPointForCoordinate(CLLocationCoordinate2D(latitude: 0.0, longitude: 180.0)).x
    }
    let height = bottomRightMapPoint.y - topLeftMapPoint.y
    let size = MKMapSize(width: width, height: height)
    return MKMapRect(origin: topLeftMapPoint, size: size)
    

    Taking an MKCoordinateRegion, converting it into an MKMapRect with the code above, and then turning it back into an MKCoordinateRegion using MKCoordinateRegionForMapRect() gives me very good agreement between the input region and the output region everywhere on the map.

提交回复
热议问题