MKMapView 边界

MKMapView Bounds

我将从 Google 地图转到 Apple 地图。 Google 地图可以根据东北和西南坐标更新相机,如下所示:

let bounds = GMSCameraUpdate.fit(GMSCoordinateBounds(northEastSouthWestBounds), with: .zero)
self.mapView.moveCamera(bounds)

我知道我可以使用 setVisibleMapRect(_:animated:) 并且它需要一个 MKMapRect。我真正的问题是如何根据东北坐标(CLLocation)和西南坐标(CLLocation)创建 MKMapRect

构造一个MKMapRect from your coordinates and pass that to either setVisibleMapRect(_:animated:) or setVisibleMapRect(_:edgePadding:animated:).

要从不同点类型的数组创建 MKMapRect

import MapKit

extension Array where Element == CLLocationCoordinate2D {
    func mapRect() -> MKMapRect? {
        return map(MKMapPoint.init).mapRect()
    }
}

extension Array where Element == CLLocation {
    func mapRect() -> MKMapRect? {
        return map { MKMapPoint([=10=].coordinate) }.mapRect()
    }
}

extension Array where Element == MKMapPoint {
    func mapRect() -> MKMapRect? {
        guard count > 0 else { return nil }

        let xs = map { [=10=].x }
        let ys = map { [=10=].y }

        let west = xs.min()!
        let east = xs.max()!
        let width = east - west

        let south = ys.min()!
        let north = ys.max()!
        let height = north - south

        return MKMapRect(x: west, y: south, width: width, height: height)
    }
}