How to feed a location into an MKMapView

mapsNow that we know how to read a location from our device, here’s how to display that location in a Map View. All we need is a referenced MKMapView in your storyboard, and to import the MapKit framework into our project / class.

For the map view to display our coordinates, we need to create an MKCoordinateRegion and give it those coordinates. We can optionally pass Delta values for longitude and latitude which will specify how zoomed in the map view will appear. Smaller values are closer, larger values are further away from our region.

This method takes a CLLocation from our previous step and sets them in our map view:

- (void)updateMapView:(CLLocation *)location {
    
    // create a region and pass it to the Map View
    MKCoordinateRegion region;
    region.center.latitude = location.coordinate.latitude;
    region.center.longitude = location.coordinate.longitude;
    region.span.latitudeDelta = 0.001;
    region.span.longitudeDelta = 0.001;
    
    [self.mapView setRegion:region animated:YES];
}

Setting a Pin on the centre

Notice how the above displays the map correctly, but no red centre pin. To do that we need to create an MKPlacemark with the same longitude and latitude as above:

This content is for members only.

This method is called asynchronously and hence uses a block which is called upon completion. In it we’ll access the place marks array and grab the last object, then access its many exciting properties. Note that sometimes that information is not available, hence I’m querying the first one before updating a label (which would show NULL if no information is present).

I’ve created a Demo Project on GitHub called Locations – feel free to fork and examine how it works.





Leave a Reply