Learn how to do MapView in Swift

MapView in Swift is the important portion. Learn how to do MapView in Swift of a particular city. We will proceed with a example as follows:-

In this tutorial we will display a portion of the city India and we will add an annotation of the Rajkot.

step 1: open xcode File → New → Project → SingleViewApplication & select language as a swift during creation of project.


 

 

Screen Shot 2015-03-14 at 5.41.41 PM

 

 

Step 2: add framework for map view from target → Build Phases → Link Library with library → +


 

 

Screen Shot 2015-03-14 at 5.48.30 PM

 

 

Step 3: add MapKit View from objects in storyboard .The StoryBoard should look like this.

Select the Assistant Editor and open ViewController.swift. Ctrl and drag from the Segmented Control to
the ViewController.swift and create the following Outlet.


 

Screen Shot 2015-03-14 at 5.54.41 PM

In view controller it look like this:

class ViewController: UIViewController {

@IBOutlet var mapView: MKMapView!

override func viewDidLoad()

{ }

Step 4: Change the viewDidLoad method in

override func viewDidLoad() {

super.viewDidLoad()

//The latitude and longitude of the city of India is assigned to location constant using the CLLocationCoordinate2d struct

let location = CLLocationCoordinate2D(

latitude: 22.30,

longitude:70.77)

//The span value is made relative small, so a big portion of London is visible. The MKCoordinateRegion method defines the visible region, it is set with the setRegion method.

let span = MKCoordinateSpanMake(0.05, 0.05)

let region = MKCoordinateRegion(center: location, span: span)

mapView.setRegion(region, animated: true)

//An annotation is created at the current coordinates with the MKPointAnnotaition class. The annotation is added to the Map View with the addAnnotation method.

let annotation = MKPointAnnotation()

annotation.setCoordinate(location)

annotation.title = “rajkot”

annotation.subtitle = “india”

mapView.addAnnotation(annotation)

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated.

}

step 5: Build and Run the project, The city of India, including the ann otation will be diplayed.


 

Screen Shot 2015-03-14 at 6.00.33 PM

 

Hope You Enjoy it!!!!