How to Load MKMapKitView & add Pin or Marker using swift

Loading map on your iOS application’s MKMapKitView is very easy. Just drug and drop. To add a pin or marker, write some simple codes in swift. Let’s begin:

Create a new “Single View” project in Xcode. Select swift as language.

  1. Open Main.stroyboard from Project explorer. You will see the ViewController.
    MKMapKitView
  2. Focus on Object library. It is at bottom right corner of Utility panel. Find out Map Kit View. If you can’t find out it, take help of filter box. Filter box is located at the bottom of the Object library. Check the screenshot.
    MKMapKitView
  3. Drag and drop the Map Kit View in View Controller. Resize Map Kit View so that it fills the full ViewController. Add appropriate auto layouts.Add framework
  4. Now we have to import MapKitView framework in our project. So,  select project (1) > Target app (2). Open Build Phases tab (3).
  5. Expand Link Binary with Libraries (5). Click + button (5)Find MapKit framework
  6. Search for MapKit.framework. Once you find the framework, select it. Then click Add button.
  7. Now run the app.

You application will be loaded. You will see a nice map on your simulator.

How to add Marker or Pin on MKMapKitView

We’ll add a marker or pin on MKMapKitView. Suppose we want to show the pin on Lanai island of Hawaii. Latitude and longitude of the location are 20.836864 and -156.874269. It will require only 3 steps.

IBOutlet

  1. Make an IBOutlet of MKMapKitView in ViewController.swift file. I used mapView as outlet name.

Import MapKit in ViewController:

2. Now write a method to load the pin / Marker:

3. Initially, the map focuses user’s current location. However, we’ve to move the focus to the point where our pin is located. To do that, add another method:

Finally call above 2 methods in ViewDidLoad.

Run the app.

You will see the pin in on lanai Island of Hawaii. You may be wondering, where do I get latitude longitude. Take help of google map to find latitude and longitude of any location on earth.

Happy Coding!!!

Leave a Reply