如何自动缩放 mapView 以显示覆盖

how to automatically zoom mapView to show overlay

我可以在 mapView 上绘制多边形,但是我需要定位多边形并手动对其进行缩放。有没有办法自动执行此过程,例如在中心调整多边形?我浏览了互联网并阅读了一些相关文章,其中大多数是基于折线和点的。任何形式的帮助将不胜感激,因为我正在寻找解决方案一段时间。提前致谢。

使用以下方法在 mapView 上绘制多边形:-

func drawFence(coordinates: UnsafePointer<CLLocationCoordinate2D>, count: Int) {
        let makePoly = MKPolygon(coordinates: coordinates, count: count)
        mapview.addOverlay(makePoly)
    }

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    guard let polyOverlay = overlay as? MKPolygon else { return MKOverlayRenderer() }
    let polyRender = MKPolygonRenderer(polygon: polyOverlay)
    polyRender.fillColor = #colorLiteral(red: 0.9764705882, green: 0.09803921569, blue: 0.2588235294, alpha: 0.6)
    polyRender.strokeColor = #colorLiteral(red: 0.9764705882, green: 0.09803921569, blue: 0.2588235294, alpha: 1)
    polyRender.lineWidth = 2
    return polyRender
}

如果您想放大特定叠加层,您可以:

let insets = UIEdgeInsets(top: 50, left: 50, bottom: 50, right: 50)

func zoom(for overlay: MKOverlay) {
    mapView.setVisibleMapRect(overlay.boundingMapRect, edgePadding: insets, animated: true)
}


如果您想缩放地图以显示所有叠加层,您可以这样做:

func zoomForAllOverlays() {
    guard let initial = mapView.overlays.first?.boundingMapRect else { return }

    let mapRect = mapView.overlays
        .dropFirst()
        .reduce(initial) { [=11=].union(.boundingMapRect) }

    mapView.setVisibleMapRect(mapRect, edgePadding: insets, animated: true)
}

例如,添加了两个叠加层(在 NYC 和 Stamford 上),我调用了该例程,结果为:


顺便说一句,我知道问题是关于 Polygon 叠加层的,但无论叠加层类型如何,该技术都有效。为演示目的创建 Circle 叠加层更简单。