- Getting Started with Core Location and Map Kit
- The Core Location Manager
- Forward and Reverse Geocoding
- Working with Map Kit
- Wrapping Up
The Core Location Manager
As the first step in working with location data, we’ll focus on Core Location. Remember, Core Location is primarily a data-oriented framework. This means we’ll be dealing with coordinates, text strings, and number values instead of visual location information like maps. Later in the Map Kit section, we’ll discuss how to use some of the data sources we learn about with Core Location in combination with Map Kit, and how to visually represent location information on a map.
I’ve mentioned the Core Location Manager (CLLocationManager) a few times. The CLLocationManager is responsible for controlling the flow and frequency of location updates provided by location hardware. Simply put, the location manager generates location objects (CLLocation objects) and passes them to its delegate whenever a certain set of criteria is met. These criteria are determined by how you configure and start your location manager.
The CLLocationManager is typically used to generate location data while working with one of the following services.
- Standard Location Service
- Significant Location Change Monitoring
- Heading Monitoring
- Region Monitoring
Standard Location Service
The standard location service is one of the most common uses of the location manager. Used to determine a user’s current location as needed for nearby searches or check-in locations, the standard location service can be configured with a desired accuracy and distance filter (which is the threshold used to determine when a new location should be generated). When a device moves beyond the configured distance filter, the standard location service triggers a new location and calls the necessary delegate methods. After creating the location manager and configuring the desired properties, call startUpdatingLocation to begin location services. The following code block demonstrates how to set up a new location manager using the standard location service:
1 //Create a new location manager 2 locationManager = [[CLLocationManager alloc] init]; 3 4 // Set Location Manager delegate 5 [locationManager setDelegate:self]; 6 7 // Set location accuracy levels 8 [locationManager setDesiredAccuracy:kCLLocationAccuracyKilometer]; 9 10 // Update again when a user moves distance in meters 11 [locationManager setDistanceFilter:500]; 12 13 // Configure permission dialog 14 [locationManager setPurpose:@"My Custom Purpose Message..."]; 15 16 // Start updating location 17 [locationManager startUpdatingLocation];
In this code block, line 2 allocates a new CLLocationManager and saves it as an instance variable named locationManager. In line 5 we set the location manager delegate as self, which means this class must observe the CLLocationManager-Delegate protocol (covered in the section below, Responding to New Information from the Core Location Manager). Next, in line 8 we set the desired accuracy of our location manager to 1 kilometer, and in line 11 we set the distance filter of our location manager to 500 meters.
While the distance filter can be almost any value, I personally have found that setting your distance filter to half the distance of your desired accuracy typically generates a fairly accurate sample of locations as needed by the location accuracy.
In line 14 we set the custom purpose message. Remember, this message will be shown in the location permission dialog as seen in Figure 4.3 and should be used to describe why your app needs access to a user’s location—especially when it’s not readily apparent. Finally, in line 17 we start updates on the location manager by calling startUpdatingLocation.
Significant Location Change Monitoring
The location manager of a significant location change service sends new locations to the delegate whenever it detects the device has significantly changed position. The location manager provides a starting location as soon as this service is started and future locations are only calculated and sent to the delegate when the device detects new Wi-Fi hotspots or cellular towers. While slightly similar to the standard location service in functionality, this method is much more aggressive in power management and is highly efficient. While the standard service continuously monitors a user’s location to determine when the distance filter threshold is crossed, the significant location change disables location services between new location events (because location events are determined when new connections are located by the cellular and Wi-Fi antennae). As an added bonus, unlike the standard location service, the significant change monitoring service will wake up an app that’s suspended or terminated and allow the app to execute any necessary background processes.
The code needed to set up a significant location change monitoring is much simpler, essentially because the significant location change service is largely handled by the core operating system. Remember, the significant location change monitoring service automatically generates new locations when the radio antennae detect new connection sources (cellular or Wi-Fi). That means the significant location change service will ignore the accuracy and distance filter properties of the location manager (the accuracy will always be the best available by the sources used). The following code block demonstrates how to set up a location manager that monitors significant location changes:
1 //Create a new location manager 2 locationManager = [[CLLocationManager alloc] init]; 3 4 // Set Location Manager delegate 5 [locationManager setDelegate:self]; 6 7 // Configure permission dialog 8 [locationManager setPurpose:@"My Custom Purpose Message..."]; 9 10 // Start updating location 11 [locationManager startMonitoringSignificantLocationChanges];
Very similar to the previous code block, starting the significant location change service simply involves creating a new location manager (line 2), setting the delegate (line 5), configuring an optional custom purpose message (line 8), and then calling the method, startMonitoringSignificantLocationChanges in line 11 (instead of startUpdatingLocation). Just like the standard location service, the significant location change service interacts with its delegate using the same methods, which is covered in the section that follows, Responding to New Information from the Core Location Manager.
Heading Monitoring
Heading information is a little different than the other location-based data types generated by the location manager. Unlike the previous services, the heading monitoring service only generates new heading information (direction information relative to magnetic north or true north). The heading object (CLHeading) is created using the device’s magnetometer (compass) and does not contain a reference to the latitude and longitude coordinates of the device.
Just like with other location services, not all devices are equipped with a magnetometer, especially older generation models. You should first check to see if heading services are available by calling [CLLocationManager headingAvailable], and if heading services are required for your app’s function (such as a compass app) you should add the value magnetometer to your app’s info property list.
One of the reasons heading monitoring exists as a separate service—besides separate hardware—is because doing so allows additional performance optimization. In most location-aware apps, you don’t need to know the device heading with incredible accuracy. The majority of apps are able to get by on the generic speed and heading information generated in the standard and significant location change services. In these cases, the course and speed values managed by the CLLocation object are simply extrapolated based on the previous location coordinate (distance moved, direction moved). This means if your user is standing still, the CLLocation object is likely to hold invalid heading information.
Because heading monitoring is a separate service, however, you can give your users the option of turning on additional heading information as needed. This practice is observed in the native Google Maps app on the iPhone and iPad. When a user taps the location button once, the map zeros in on their current location. If they tap the location button again, the Google Maps app enables heading monitoring to indicate the direction the device is facing.
Starting a heading monitoring service is just like starting updates on a standard location service. The process involves creating a new location manager, assigning the delegate, setting your desired accuracy and threshold filter (in degrees changed), and calling startUpdatingHeading. Because the heading is dependent on the orientation of your device (landscape versus portrait), the location manager also allows you to set the desired heading orientation. The following code block demonstrates how to set up a new heading monitoring service:
1 if([CLLocationManager headingAvailable]){ 2 3 // Create a new Location Manager and assign delegate 4 headingManager = [[CLLocationManager alloc] init]; 5 [headingManager setDelegate:self]; 6 7 //Send all updates, even minor ones 8 [headingManager setHeadingFilter:kCLHeadingFilterNone]; 9 10 // Set heading accuracy 11 [headingManager setDesiredAccuracy:kCLLocationAccuracyBest]; 12 13 // Set expected device orientation 14 [headingManager setHeadingOrientation: CLDeviceOrientationLandscapeLeft]; 15 16 // Start updating headings 17 [headingManager startUpdatingHeading]; 18 } 19 else 20 NSLog(@"Heading not available");
You’ll notice this code block is similar to the standard location service. The first thing we do is check to see if heading services are available by calling the CLLocationManager class method headingAvailable in line 1. Next, in lines 4 and 5 we create a new CLLocationManager object and assign the delegate to self. In line 8 we set up our desired heading filter. This value specifies the minimum heading change in degrees needed to trigger a new heading event. In line 8 we set this option to the constant, kCLHeadingFilterNone. This simply sets the filter to nothing allowing us to obtain every change detected (no matter how minor) from the magnetometer. By default, this filter value is set to 1 degree.
In line 14 we set the expected orientation of our device to landscape left. The orientation will default to portrait, and if your device allows for rotation you should detect device rotations and reassign the heading orientation when appropriate. Finally, in line 17 we start updating our heading information. This begins calling the delegate method, locationManager:didUpdateHeading: when the filter threshold condition is met.
Region Monitoring
One of the newest features available in iOS 5 is the ability to add region-based monitoring services to a location manager. Region monitoring allows you to monitor a device’s interaction with the bounds of defined areas or regions; specifically, the location manager will call didEnterRegion and didExitRegion on its assigned delegate when the bounds of monitored regions are crossed.
This new functionality allows for all sorts of app opportunities from auto-check-in services to real-time recommendations (for example, you’re walking past a good coffee shop and an app on your phone knows that you like coffee). In fact, the new Reminders app for iOS 5 uses this functionality in combination with Siri (the iPhone 4S digital assistant) to carry out requests such as “Remind me when I get home that I need to take out the trash,” or “Remind me when I leave the office that I need to call my wife and tell her I’m on my way.” In these examples, Siri simply defines a region in a core location manager for the locations home and the office and sets up a reminder to trigger when those regions detect the appropriate didExitRegion or didEnterRegion events.
The process for monitoring regions is very similar to the other services we monitored. Instead of setting up distance filters or depending on cell towers to trigger new location events, however, we define a specific circular region (or regions) based on a set of latitude and longitude coordinates and a radius in meters.
The following code block demonstrates how to monitor for a region. This example assumes that you already know the latitude and longitude coordinates of your target region. Later, we’ll cover how to generate these values using human-readable address strings, but for now, let’s just assume you’ve memorized that Apple’s main campus is located at the latitude and longitude coordinates of (37.331691, −122.030751).
1 // Create a new location manager 2 locationManager = [[CLLocationManager alloc] init]; 3 4 // Set the location manager delegate 5 [locationManager setDelegate:self]; 6 7 // Create a new CLRegion based on the lat/long 8 // position of Apple's main campus 9 CLLocationCoordinate2D appleLatLong = CLLocationCoordinate2DMake(37.331691, -122.030751); 10 CLRegion *appleCampus = [[CLRegion alloc] initCircularRegionWithCenter:appleLatLong radius:100 identifier:@"Apple"]; 11 12 // Start monitoring for our CLRegion using best accuracy 13 [locationManager startMonitoringForRegion:appleCampus desiredAccuracy:kCLLocationAccuracyBest];
In this example, we set up the location manager and delegate in lines 2 through 5. In line 9 we create a new CLLocationCoordinate2D using the latitude and longitude coordinates for Apple’s main campus. Next, in line 10 we allocate a new CLRegion. Notice we initialize this region as a circular region with the radius of 100 meters. This method also allows us to assign an identifier we can use to refer to the region at a later time (in the event you’re monitoring more than one region in your location manager). Finally, in line 13 we simply start the monitoring service for our CLRegion by calling startMonitoringForRegion:desiredAccuracy.
Responding to New Information from the Core Location Manager
As you’ve learned, the location manager is delegate based. This means the location manager calls methods on its assigned delegate whenever new location, heading, or region information is available. These delegates are defined in the protocol CLLocationManagerDelegate.
Table 4.3 outlines the delegate methods used in the standard location service, significant location change monitoring service, heading monitoring service, and the region monitoring service described in this chapter. By implementing these methods in the class used as the assigned delegate, you can update your UI or save relevant course information as needed by your app.
Table 4.3. Core Location Manager Delegate Protocol Methods
Method |
Description |
locationManager:didUpdatetoLocation:fromLocation: |
Called by both the standard location service and significant location change service when new CLLocation objects are generated. Both of these services pass in the new CLLocation object (toLocation) as well as the previous location object (fromLocation) |
locationManager:didFailWithError: |
Called by the standard location service and the significant location change service when an error occurs. An error could be the result of conditions such as bad hardware or an interruption in service during a location call. |
locationManager:didUpdateHeading: |
Called by the heading monitoring service whenever a new heading is generated based on the heading filter threshold. The heading object passed to this delegate (CLHeading) contains relative directions to both true and magnetic north along with the x, y, and z components of that heading. |
locationManager:didEnterRegion: |
Called by the location manager when a device crosses into a monitored region. |
locationManager:didExitRegion: |
Called by the location manager when a device exits a monitored region. |
locationManager:monitoringDidFailForRegion:withError: |
Called when region monitoring fails due to an error. |
locationManager:didChangeAuthorizationStatus: |
Called when the location permissions for this app are changed. |