Search code examples
swiftmapkitmkoverlay

Why region is changed when I am setting current region?


I have put a button so that add a circle overlay to given point. However I don't know why but while region didn't change my overlay could not be seen.

I couldn't find a func that refresh or reload map. So finally I decided to change map region so slightly that user will not be disturbed. (A little bit zoom out for example).

self.mapView.setRegion(mapView.region, animated: true)

I expect that above code do not change the map region however it does, and also I tried this,

self.mapView.setRegion(MKCoordinateRegion(mapView.visibleMapRect), animated: true)

This also changed the map's region.

What can I do ?

And This is how I add my overlays

func addCircles() {

    let center = self.myPinView.center
    let origin = self.mapView.convert(center, toCoordinateFrom: mapView)
    let overlay1 = MKCircle(center: origin, radius: 3)
    let overlay2 = MKCircle(center: origin, radius: 7.5)
    let overlay3 = MKCircle(center: origin, radius: 15)
    self.mapView.addOverlay(overlay1)
    self.mapView.addOverlay(overlay2)
    self.mapView.addOverlay(overlay3)

}

And this is my delegate func

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {

if overlay is MKCircle {

        let circle = MKCircleRenderer(overlay: overlay)
        circle.fillColor = circle.fillColor = UIColor(red: 255, green: 0, blue: 0, alpha: 0.6)
        circle.strokeColor = .red
        return circle

    } else {
        return MKOverlayRenderer()
    }

}

Solution

  • Actually I solve my spesific problem with a different view. My initial problem was, after user pick a position I wanted to draw a circle. However my overlays don't appear until the map region changed. I was trying to draw this circles immediately. And the most user friendly solution that I found, set mapView center to overlay's center.

    self.mapView.setCenter(origin, animated: false)
    

    In this way, after user pick a position, immediately map focus on this position and overlays are displayed.