Tag Archives: Core Location

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:

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.

How to read the current location of an iOS device

Thanks to the Core Location framework we can get the current location of our device. We need to create a CLLocationManager object and start it. Its delegate method will return CLLocation objects which among other items will contain the longitude and latitude of our device.

location

Here’s how to do it. Let’s create the manager as a property (self.manager) and initialise it with this custom method:

This content is for members only.

In the first method all I’m doing is to display the longitude and latitude in two labels. Both are float values, derived from a CLLocation object that is available in the locations array (this is new in iOS 7). This array contains previous location objects as well and is amended every time this method is called. The most current location is at the end of the array (we get it via [locations lastObject]).

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