Using Current location in Apple Maps
I was updating one of my iOS apps that used to open up the Maps Application to show directions from the current location to a set of coordinates.
Before Apple Maps was introduced we could use “Current Location” as a way for Maps to use the users current location (http://maps.google.com/maps?saddr=Current%%20Location&daddr=51.535455,-0.247557) this no longer works in Apple Maps.
To get round this problem I had to use CLLocationManager to get the current location and then use that in the URL.
Start off by adding the CoreLocation framework.
MapViewController.h
@interface MapViewController : UIViewController<MKMapViewDelegate, CLLocationManagerDelegate>{ CLLocationManager *locationManager; } |
MapViewController.m
-(void)viewDidLoad{ locationManager = [[CLLocationManager alloc] init]; locationManager.delegate = self; locationManager.desiredAccuracy = kCLLocationAccuracyBest; [locationManager startUpdatingLocation]; } - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { NSLog(@"didUpdateToLocation: %@", newLocation); currentLocation = newLocation; [locationManager stopUpdatingLocation]; //Added to prevent continuous updating as we only needed the location once. } -(IBAction) viewinMaps { Class itemClass = [MKMapItem class]; if (itemClass && [itemClass respondsToSelector:@selector(openMapsWithItems:launchOptions:)]) { // iOS 6 MKMapItem available NSString *locationQuery = [NSString stringWithFormat:@"http://maps.apple.com/maps?saddr=%f,%f&daddr=51.535455,-0.247557", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude]; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:locationQuery]]; } else { // pre-iOS 6 NSString *locationQuery = [NSString stringWithFormat:@"http://maps.google.com/maps?saddr=Current%%20Location&daddr=51.535455,-0.247557"]; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:locationQuery]]; } } |