简体   繁体   中英

How can I zoom to a particular location on a map on button click. I am using swift and MapKit

This is how the button action looks in my view controller.

     func mapButtonClickedInScrollview(sender: UIButton) {
         let myWorldViewController = MyWorldViewController(nibName: "MyWorldViewController", bundle: nil)
         self.navigationController?.pushViewController(myWorldViewController, animated: true)
     }

This is how my map looks which is set in another view controller(ie MyWorldViewController):

   [enter link description here][1]

So when I click that button, i should go to another controller and it should automatically zoom to that car pin which is shown in the image above. Any help would be appreciated!

     [1]: http://i.stack.imgur.com/0Nddd.png

Assuming you have a navbar, first create a push segue from origin to destination view controller, don't reuse the same VC since you'll need more logic behind it, then give it an identifier, lets say expandedAnnotation . Then create a "selectedAnnotation property on your current VC MyWorldViewController
You will need to use MapKit's didSelectAnnotationView and find the annotation you selected by, (example on a project I have where my annotations are Artworks (custom class name))

func mapView(mapView: MKMapView!, didSelectAnnotationView view: MKAnnotationView!) {
    if let annotation = view.annotation as? Artwork {
        selectedAnnotation = annotation
        performSegueWithIdentifier("expandedAnnotation", sender: self)
    }
}

Then, in your overriden prepareForSegue function, pass the annotation to the destination viewcontroller. Of course first create a property for the annotation in the destination view controller.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "expandedAnnotation") {
        let destinationVC = segue.destinationViewController as! DestinationViewController
        destinationVC.annotation = selectedAnnotation
    }

And thats it, in your destinationVC viewDidLoad , add the annotation to the mapView and center its region around it. Good luck

Pass coordinate of the point of interest to your new view controller and in it's map view use setRegion . The code might look like this:

var region = MKCoordinateRegion(center: myCoordinate, span: 200)
region = mapView.regionThatFits(region)
mapView.setRegion(region, animated: true)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM