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

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


我知道我可以使用setVisibleMapRect(_:animated:),它包含一个MKMapRect。我真正的问题是如何基于东北坐标(CLLocation)和西南坐标(CLLocation)创建MKMapRect

最佳答案

从坐标构造一个MKMapRect并将其传递给setVisibleMapRect(_:animated:)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($0.coordinate) }.mapRect()
    }
}

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

        let xs = map { $0.x }
        let ys = map { $0.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)
    }
}

10-08 04:53