Creating a Location Map

Free iOS Development Tutorial

Explore the steps to add a map to your iOS app, including adding the MapKit framework, setting a custom location, and defining location coordinates with this comprehensive guide to iOS Development.

This exercise is excerpted from Noble Desktop’s past app development training materials and is compatible with iOS updates through 2021. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

Topics covered in this iOS Development tutorial:

Adding the MapKit framework, Adding a map view, Setting a custom location, Defining location coordinates, Adding Auto Layout

Exercise Preview

ex prev location map

Exercise Overview

In this exercise, we’ll add a map to our app showing the location of the Jive Factory.

Full-Stack Web Development Certificate: Live & Hands-on, In NYC or Online, 0% Financing, 1-on-1 Mentoring, Free Retake, Job Prep. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

Getting Started

  1. If you completed the previous exercise you can skip the following sidebar. We recommend you finish the previous exercises (1B–2C) before starting this one.

    If you completed the previous exercise, Jive Factory.xcodeproj should still be open. If you closed it, re-open it (from yourname-iOS Dev Level 2 Class > Jive Factory).

    If You Did Not Complete the Previous Exercises (1B–2C)

    1. Close any files you may have open and switch to the Desktop.
    2. Navigate to Class Files > yourname-iOS Dev Level 2 Class.
    3. Duplicate the Jive Factory Ready for Location Map folder.
    4. Rename the folder to Jive Factory.
    5. Open Jive Factory > Jive Factory.xcodeproj.

Adding the MapKit Framework

In order to have a map in our app, we need to add an Apple-provided framework, called the MapKit.framework, to our project. It will give us additional functionality for manipulating the map such as zooming and pinpointing locations. A framework can be a collection of libraries or a collection of code, and it can contain new UI elements or images.

  1. Click on the Jive Factory project name in the Project navigator. This opens the Project Settings Editor.

    open project settings editor

  2. If the projects and targets are not showing, click Show projects and targets list show hide document outline icon (it’s in the upper left above Identity).

  3. Under Targets, make sure Jive Factory is selected.

    targets jivefactory

  4. Click on the Build Phases tab at the top.
  5. Expand the Link Binary With Libraries section.
  6. Towards the bottom left of the section, click the Add items button add button.
  7. In the search bar at the top, type: map
  8. In the results, double–click on MapKit.framework to add it.
  9. In the Project navigator, notice a Frameworks folder has been added containing MapKit.framework

Adding a Map View

  1. In the Project navigator, click on Main.
  2. In order to apply the Map Kit View we’ll add, make sure you are zoomed into 100%.
  3. In the Object library object library icon search, type in: map
  4. From the Object library object library icon, drag Map Kit View onto the Map View Controller in the Editor area. Be careful not to drag onto the bottom of the view (where the tab is) or position it so that it overwrites the existing view. It should look something like this when you’re dragging:

    drag MapView

TIP: If you accidentally overwrote the existing view, hit Cmd–Z to undo and try adding the Map Kit View again.

  1. We want the map to fill the iPhone screen. Drag out the handles to resize the Map View to the size of the screen.

  2. Make sure the Map Kit View is still selected in the Editor.
  3. In the Utilities area, click on the Attributes inspector tab attributes inspector icon.
  4. In the Map View section, next to Shows check on User Location.
  5. Let’s test this out. Click the Run button.
  6. When the Simulator finishes loading, click on the Map tab.
  7. If you get an alert asking to use your current location, click OK.

    Because we are using the Simulator, it will not show our current location. On a phone, it would show the user’s actual location.

  8. Let’s test out the zooming. To simulate zooming in the Simulator, hold Option. Two gray circles (representing two fingertips in a pinching action) will appear. Click and drag the mouse to simulate pinching. Cool!

Setting the Jive Factory Location

What we actually want to do is show the location of the Jive Factory (not the user’s current location). For that we’ll have to write some code. First we need to create a new class.

  1. Switch back to Xcode.
  2. In the Project navigator, select BandDetail.swift. (We want the file to be added after this file, that’s why we had you select it.)
  3. Hit Cmd–N.
  4. Double–click Cocoa Touch Class to choose it.
  5. From the Subclass of menu, choose UIViewController (or start typing it and let Xcode autocomplete it for you).
  6. Edit the name of the Class to be: MapViewController
  7. Click Next.
  8. You should already be in the Jive Factory folder, so click Create.
  9. Notice MapViewController has been added in the Project navigator.
  10. In the Project navigator, click on Main.
  11. Deselect everything by clicking on a blank area of the Editor.
  12. Select the Map View Controller by clicking on the top bar, giving the controller a blue outline.
  13. In the Utilities area, click on the Identity inspector tab identity inspector icon.
  14. Under Custom Class, next to Class, start typing Map. Xcode should autocomplete to MapViewController and you can hit Return to apply it. (If it doesn’t autocomplete, just type it.)
  15. If the Document Outline is open, click Hide Document Outline show hide document outline icon.
  16. At the top right of the window, selec the Adjust Editor Options button assistant editor icon and choose the Assistant option.
  17. If MapViewController.swift isn’t showing in the Assistant editor on the right, click the menu bar at the top of the **MapViewController* view in the storyboard and choose it.
  18. Below the import UIKit statement (around line 10) add the following bold code:

    import UIKit
    import MapKit
    
    class MapViewController: UIViewController {
    
  19. Hold Control and drag from the MK Map View on the Map View Controller, releasing in the code below class MapViewController: UIViewController { as shown below:

    insertoutlet mapview

  20. In the menu that pops up, set the following:

    Connection: Outlet
    Name: jiveMapView
    Type: MKMapView
    Storage: Weak
  21. Click Connect.
  22. Now let’s open the MapViewController file from the Project Navigator to set up the view controller.

Defining Location Coordinates

Now we want to define the coordinates of the Jive Factory. We need to define three values. The latitude and longitude determines where the location is, and the span tells Swift how far to zoom into the map. We’ll define these values as constants.

  1. Go to File > Open.
  2. Navigate to Desktop > Class Files > yourname-iOS Dev Level 2 Class > Code Snippets and open mapCoordinates.txt.
  3. Press Cmd–A to select all the code.
  4. Press Cmd–C to copy it.
  5. Close the file.
  6. In the Project navigator, select MapViewController.swift.
  7. Find the @IBOutlet weak var jiveMapView: MKMapView!.
  8. Make some space above it, then paste the code as shown below:

    class MapViewController: UIViewController {
    
       let jiveLatitude = 40.72004
       let jiveLongitude = -74.003912
       let jiveSpan = 0.05
    
       @IBOutlet weak var jiveMapView: MKMapView!
    

    This code defines three constants: jiveLatitude, jiveLongitude and jiveSpan. To get the latitude and longitude coordinates of an address, you can use a website such as itouchmap.com/latlong.html or latlong.net

    We’re going to use classes provided for us in the MapKit.framework to specify our location. First we are going to use the MKCoordinateRegion class. An MKCoordinateRegion is made up of a center point and a span.

  9. Find the viewDidLoad method.
  10. Add the following bold code at the end of the method to declare a region, replacing the comment line:

    override func viewDidLoad() {
       super.viewDidLoad()
    
       var jiveRegion = MKCoordinateRegion()
    }
    

    This code created a jiveRegion object of the type MKCoordinateRegion.

  11. We need to create a center point for our region. Add the following bold code:

    override func viewDidLoad() {
       super.viewDidLoad()
    
       var jiveRegion = MKCoordinateRegion()
       var center = CLLocationCoordinate2D()
    }
    
  12. After that, add the following code to set the center’s latitude and longitude:

       var jiveRegion = MKCoordinateRegion()    
       var center = CLLocationCoordinate2D()
       center.latitude = jiveLatitude
       center.longitude = jiveLongitude
    }
    
  13. Below that, add the following bold code to create a span:

       center.longitude = jiveLongitude
       var span = MKCoordinateSpan()
    }
    
  14. After that add the following bold code to set the span’s latitude and longitude:

       var span = MKCoordinateSpan()
       span.latitudeDelta = jiveSpan
       span.longitudeDelta = jiveSpan
    }
    
  15. Next we need to set the center and span values back onto the jiveRegion object. Add the following bold code:

       span.longitudeDelta = jiveSpan
    
       jiveRegion.center = center
       jiveRegion.span = span
    }
    
  16. Lastly, we need to reference the map view and set the region on it to our region. Add the following bold code:

       jiveRegion.span = span
       jiveMapView.setRegion(jiveRegion, animated: true)
    }
    
  17. Let’s test this out. Click the Run button.
  18. After the Simulator loads, click the Map tab. The map is centered over the Jive Factory’s location in New York, but it’s missing the location indicator/pin. That’s because we still need to create an annotation.
  19. Switch back to Xcode.
  20. After the code we added to set the region to our region, add the following bold code to create an annotation:

       jiveMapView.setRegion(jiveRegion, animated: true)
    
       let jivePoint = MKPointAnnotation()
    }
    
  21. We need to set three values on this annotation (coordinate, title, subtitle). Add the following bold code:

       let jivePoint = MKPointAnnotation()
       jivePoint.coordinate = center
       jivePoint.title = "The Jive Factory"
       jivePoint.subtitle = "580 Lispenard, NY, NY 10013"
    }
    
  22. Finally, we need to add this annotation to our map. Add the following bold code:

       jivePoint.subtitle = "580 Lispenard, NY, NY 10013"
       jiveMapView.addAnnotation(jivePoint)
    }
    
  23. Click the Run button.
  24. After the Simulator loads, click the Map tab.
  25. Check it out! We’ve got our location pinpointed! Click on the red pin to see that it also shows the title and subtitle we specified.

Adding Auto Layout

We can use Auto Layout to maintain consistent alignment across different screen sizes.

  1. Select the MK Map View on the storyboard.
  2. At the bottom right of the Editor, click the Add new constraints button pin button.
  3. In the options that pop-up, uncheck Constrain to margins if it isn’t already. Make sure all four constraint values are set to 0.
  4. At the top of the options pop up, under Add New Constraints, notice the four sets of red dotted lines surrounding a small white box, between the values. Click on all four red lines.
  5. At the bottom, click Add 4 Constraints as shown:

    map add constraints

    NOTE: This pins the sides of the map to the edges of the View. This will make sure the map fills the View at any screen size.

  6. We know our map looks good on iPhone 13 Pro, but what about on other screen sizes? Set the active scheme to iPhone 13 Pro Max.
  7. Run it.
  8. After the Simulator loads, click the Map tab to see that the map fits perfectly.
  9. Go back to Xcode.
  10. If you want to test on other screen sizes (such as iPhone SE), you can do that now. Otherwise you’re done adding a map!
  11. Keep this file open. In the next exercise, we’ll link to an external website that opens within our app.

Noble Desktop Publishing Team

The Noble Desktop Publishing Team includes writers, editors, instructors, and industry experts who collaborate to publish up-to-date content on today's top skills and software. From career guides to software tutorials to introductory video courses, Noble aims to produce relevant learning resources for people interested in coding, design, data, marketing, and other in-demand professions.

More articles by Noble Desktop Publishing Team

How to Learn iOS & Web Development

Master iOS development, web development, coding, and more with hands-on training. iOS development involves designing apps for Apple mobile devices with tools like Xcode and SwiftUI.

Yelp Facebook LinkedIn YouTube Twitter Instagram