Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to zoom into pin in MKMapView Swift

I want the location of the pin to zoom in on tapping the pin so that the location is at the center. I have no idea how to do this. Please help me.

like image 323
Palash Sharma Avatar asked Feb 08 '23 09:02

Palash Sharma


1 Answers

There's a couple of things you are trying to make happen.

  1. Figuring out which pin was tapped
  2. Centering the mapView on the tapped pin

If you have the mapView properly initiated in your project (with the view as its delegate), then both of the above points can be done by using the mapView(_:didSelectAnnotationView:) method, like this:

    func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {

        // get the particular pin that was tapped
        let pinToZoomOn = view.annotation

        // optionally you can set your own boundaries of the zoom
        let span = MKCoordinateSpanMake(0.5, 0.5)

        // or use the current map zoom and just center the map
        // let span = mapView.region.span

        // now move the map
        let region = MKCoordinateRegion(center: pinToZoomOn!.coordinate, span: span)
        mapView.setRegion(region, animated: true)
}

This method tells the delegate (your view most probably) that one of the map annotation views was selected and to move (and or zoom) to that coordinate area.

like image 69
BrotherZen Avatar answered Feb 19 '23 08:02

BrotherZen