Embedding a map with MapKit

If you would like to display a location on a map in your application, there are only a few steps you need to take. The first step is dragging a Map Kit View subview on to your main view. In this example, there is also a text field that allows the user to enter an address, and a button that calls an action that will attempt to locate the input address on the map.

Embedding MapKit

NOTE

When entering an address, you should be specific and make sure that the city name is included.

Next, you must import the Map Kit library at the top of your ViewController class like this:

import MapKit
1

In the button action, if the text field is not empty, an instance of the CLGeocoder object is created. Then it's method geocodeAddressString is called, passing in the address from the text field and the name of a function that will handle any geocoded addresses generated.

The geocodeAddressString function will attempt to return an array of locations matching the address. The handler function receives an array of any CLPlacemark objects generated by the geocodeAddressString method, and an error object that will be created if something goes wrong.

A CLPlacemark object contains information about the location found, including its latitude and longitude. To use this location with your Map Kit object, the CLPlacemark object needs to be converted to an MKPlacemark object which contains the same information formatted for use with the Map Kit API.

By calling the addAnnotation method from your Map Kit object, you can pass in your MKPlacemark object in order to centre your map on the given location. You can determine the default zoom around the marker by creating an MKCoordinateRegion object. This is done by passing your MKPlacemark object with the width and height (in meters) to a function called MKCoordinateRegionMakeWithDistance.

All you need to do then is pass the MKCoordinateRegion object back to a method in your map called setRegion. The following shows the code described above.

Embedding MapKit

This example will zoom the map to 3000 by 3000 meters, or 3km by 3km centered on what ever location it has found.

Last Updated: 12/9/2020, 6:23:23 AM