24

As the title states I would like to open the native maps app in the ios device from within my own app, by pressing a button. currently I have used an MKmapview that displays a simple pin with lat/long taken from a json file.

the code is this :

- (void)viewDidLoad {
    [super viewDidLoad]; 
}


// We are delegate for map view
self.mapView.delegate = self;

// Set title
self.title = self.location.title;

// set texts...
self.placeLabel.text = self.location.place;


self.telephoneLabel.text = self.location.telephone;
self.urlLabel.text = self.location.url;


**// Make a map annotation for a pin from the longitude/latitude points
MapAnnotation *mapPoint = [[MapAnnotation alloc] init];
mapPoint.coordinate = CLLocationCoordinate2DMake([self.location.latitude doubleValue], [self.location.longitude doubleValue]);
mapPoint.title = self.location.title;**

// Add it to the map view
[self.mapView addAnnotation:mapPoint];

// Zoom to a region around the pin
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(mapPoint.coordinate, 500, 500);
[self.mapView setRegion:region];

}`

When you touch the pin an info box appears with a title and an info button.

this is the code :

    #pragma mark - MKMapViewDelegate

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    MKPinAnnotationView *view = nil;
    static NSString *reuseIdentifier = @"MapAnnotation";

    // Return a MKPinAnnotationView with a simple accessory button
    view = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIdentifier];
    if(!view) {
        view = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
        view.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        view.canShowCallout = YES;
        view.animatesDrop = YES;
    }

    return view;
}

I want to make a method that opens the maps app with directions from the Current users location to the mapPoint above , when clicking the button in the info box above. Is that possible? Also Can I customize the look of this button? (i mean like putting a different image to the button to make it look like "press me for direction kinda" ).

Sorry if this a stupid question, but this is my first ios app and Obj-c is a totally new language to me.

thanks for all the replies in advance.

Jason Fox
  • 5,115
  • 1
  • 15
  • 34
Kostenko
  • 297
  • 1
  • 4
  • 14
  • Check this link - https://developer.apple.com/library/ios/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html – nswamy Feb 24 '14 at 09:29
  • 1
    Similar question was answered here http://stackoverflow.com/questions/15564745/how-to-open-a-apple-maps-application-with-directions-from-my-ios-application – Basheer_CAD Feb 24 '14 at 09:29

3 Answers3

48

Here is code to open Map app with directions:

Objective-C Code

NSString* directionsURL = [NSString stringWithFormat:@"http://maps.apple.com/?saddr=%f,%f&daddr=%f,%f",self.mapView.userLocation.coordinate.latitude, self.mapView.userLocation.coordinate.longitude, mapPoint.coordinate.latitude, mapPoint.coordinate.longitude];
if ([[UIApplication sharedApplication] respondsToSelector:@selector(openURL:options:completionHandler:)]) {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString: directionsURL] options:@{} completionHandler:^(BOOL success) {}];
} else {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString: directionsURL]];
}

with the mapPoint is where you want to direction to.

Swift3 or later

let directionsURL = "http://maps.apple.com/?saddr=35.6813023,139.7640529&daddr=35.4657901,139.6201192"
guard let url = URL(string: directionsURL) else {
    return
}
if #available(iOS 10.0, *) {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
    UIApplication.shared.openURL(url)
}

Note that saddr, daddr is urlencoded string of location name or location coordinate (about encode URL look at here).

directionsURL example:

// directions with location coordinate
"http://maps.apple.com/?saddr=35.6813023,139.7640529&daddr=35.4657901,139.6201192"
// or directions with location name
"http://maps.apple.com/?saddr=Tokyo&daddr=Yokohama"
// or directions from current location to destination location
"http://maps.apple.com/?saddr=Current%20Location&daddr=Yokohama"

More options parameters (like transport type, map type ...) look at here

larva
  • 4,687
  • 1
  • 24
  • 44
  • it would be maps.apple.com since ios6 (maps.google.com might work though! apple wouldn't want to brake stuff.) anwyays I'd say it'd be better to use the api michael mentioned – Daij-Djan Feb 24 '14 at 10:15
  • I tried to do this. I added an -(IBAction) to a button in my details view. the maps application opens but i get a message "Directions not Available". I used this code : - (IBAction)navigate{ NSString* url = [NSString stringWithFormat:@"http://maps.apple.com/maps?saddr=%f,%f&daddr=%f,%f",self.mapView.userLocation.coordinate.latitude, self.mapView.userLocation.coordinate.longitude, self.location.latitude, self.location.longitude]; [[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]]; } – Kostenko Feb 24 '14 at 12:08
  • Actually it worked, but I needed to change the %f with %@. Thanks so much! – Kostenko Feb 24 '14 at 12:57
  • 1
    Great answer, useful to send locations via SMS or Mail – Frank Eno Jul 12 '16 at 08:28
  • 1
    Worked for me. But be aware that `Current%20Location` should be with one percent. Or URL will not parse correctly. – Anton Ogarkov Jan 19 '18 at 12:09
  • Hi, In my app I am using a link to open Apple Maps. Directions are working fine. The problem is that voice turn by turn navigations are not working. Is it possible to do that? Thanks in advance! – Ravi Kumar Dec 14 '18 at 06:13
  • We are providing the source address and destination address in apple maps, Is there an option to the source address as user location if no direction is found for destination using Apple Maps – Nassif Mar 31 '21 at 02:11
17

You can open maps with direction using this code : (assuming your id< MKAnnotation > class has a CLLocationCoordinate2D public property named "coordinate")

MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:[annotation coordinate] addressDictionary:nil];
MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
[mapItem setName:"WhereIWantToGo"]];
NSDictionary *options = @{MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving};
[mapItem openInMapsWithLaunchOptions:options];

You can also change the button, actually you are using a standard style button :

[UIButton buttonWithType:UIButtonTypeDetailDisclosure];

But you can alloc your custom button with an image or a label :

[[UIButton alloc] initWithImage:[UIImage imageNamed:"directionIcon.png"]];
Michaël Azevedo
  • 3,874
  • 7
  • 31
  • 45
9

Here is the working code for showing directions on Apple map. It'll work for current place to your destination place and you just need to pass lat & long of destination place.

double destinationLatitude, destinationLongitude;
destinationLatitude=// Latitude of destination place.
destinationLongitude=// Longitude of destination place.

Class mapItemClass = [MKMapItem class];

if (mapItemClass && [mapItemClass respondsToSelector:@selector(openMapsWithItems:launchOptions:)])
{
    // Create an MKMapItem to pass to the Maps app
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(destinationLatitude,destinationLongitude);
    MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:coordinate addressDictionary:nil];

    MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
    [mapItem setName:@"Name/text on destination annotation pin"];

    // Set the directions mode to "Driving"
    // Can use MKLaunchOptionsDirectionsModeDriving instead
    NSDictionary *launchOptions = @{MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving};

    // Get the "Current User Location" MKMapItem
    MKMapItem *currentLocationMapItem = [MKMapItem mapItemForCurrentLocation];

    // Pass the current location and destination map items to the Maps app
    // Set the direction mode in the launchOptions dictionary
    [MKMapItem openMapsWithItems:@[currentLocationMapItem, mapItem] launchOptions:launchOptions];
}

Also, share me here, if notice any issue or we need to find out another way to done it.