Search code examples
iosswiftmapkitcore-locationmkpolygon

how to automatically zoom mapView to show overlay


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
}

Solution

  • 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)
    }
    

    enter image description here


    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:

    mapview w two overlays


    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.