how to automatically zoom mapView to show overlay

时光毁灭记忆、已成空白 提交于 2019-12-11 00:25:44

问题


I am able to draw the polygon on mapView however I need to locate the polygon and zoom it manually. Is there a way to do this process automatically like adjust the polygon in centre? I have browsed the internet and read few related articles, most of them are based on polylines and points. Any kind of help will be appreciated, as I am finding for the solution for a while. Thanks in advance.

Using the following methods to draw the polygon on 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
}

回答1:


If you’re trying to zoom into a particular overlay, you can:

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

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


If you want to zoom the map to show all the overlays, you can do:

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

    let mapRect = mapView.overlays
        .dropFirst()
        .reduce(initial) { $0.union($1.boundingMapRect) }

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

For example, having added two overlays (over NYC and Stamford), I called that routine, and it resulted in:


By the way, I know the question was about Polygon overlays, but the technique works regardless of the overlay type. It was just simpler to create Circle overlays for demonstration purposes.



来源:https://stackoverflow.com/questions/58707909/how-to-automatically-zoom-mapview-to-show-overlay

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!