In this Swift code example we will create MKMapView programmatically and will handle an event when user taps on MKAnnotationView on a MapView .
didSelectAnnotationView example in Swift
func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) { if let annotationTitle = view.annotation?.title { print("User tapped on annotation with title: \(annotationTitle!)") } }
Below is a complete code example that demonstrates how to:
- Create MKMapView programmatically,
- Determine user’s current location
- Set current region on the map
- Create MKPointAnnotation with custom title
- Drop MKPointAnnotation as a Pin at user’s current location
- Handle an event(didSelectAnnotationView) when user taps on a MKAnnotationView
MapView didSelectAnnotationView – Complete Code Example in Swift.
Drop a Pin(MKPointAnnotation) on MapView at user’s current location and handle an event when user selects an annotation view.
import UIKit import CoreLocation import MapKit class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate { var locationManager:CLLocationManager! var mapView:MKMapView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // Create and Add MapView to our main view createMapView() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) determineCurrentLocation() } func createMapView() { mapView = MKMapView() mapView.delegate = self let leftMargin:CGFloat = 10 let topMargin:CGFloat = 60 let mapWidth:CGFloat = view.frame.size.width-20 let mapHeight:CGFloat = 300 mapView.frame = CGRectMake(leftMargin, topMargin, mapWidth, mapHeight) mapView.mapType = MKMapType.Standard mapView.zoomEnabled = true mapView.scrollEnabled = true // Or, if needed, we can position map in the center of the view mapView.center = view.center view.addSubview(mapView) } func determineCurrentLocation() { locationManager = CLLocationManager() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() if CLLocationManager.locationServicesEnabled() { //locationManager.startUpdatingHeading() locationManager.startUpdatingLocation() } } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let userLocation:CLLocation = locations[0] as CLLocation // Call stopUpdatingLocation() to stop listening for location updates, // other wise this function will be called every time when user location changes. //manager.stopUpdatingLocation() let center = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude) let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) mapView.setRegion(region, animated: true) // Drop a pin at user's Current Location let myAnnotation: MKPointAnnotation = MKPointAnnotation() myAnnotation.coordinate = CLLocationCoordinate2DMake(userLocation.coordinate.latitude, userLocation.coordinate.longitude); myAnnotation.title = "Current location" mapView.addAnnotation(myAnnotation) } func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { print("Error \(error)") } func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) { if let annotationTitle = view.annotation?.title { print("User tapped on annotation with title: \(annotationTitle!)") } } }
CoreLocation and MKMapKit Video Tutorial
The below video tutorial will demonstrate how to create MapView programmatically as well as how to create MapView using the Storyboard and will walk you through the source code that determines user’s current location in greater details.
[raw_html_snippet id=”cookbookpagecoursesheader”]
Unit Testing Swift Mobile App
Apply Test-Driven Development(TDD) process to iOS mobile app development in Swift Preview this video course.