How to invoke iPhone Maps for Directions with Current Location as Start Address

后端 未结 16 1684
一整个雨季
一整个雨季 2020-12-02 03:53

I know it\'s possible to start the iPhone maps application by calling openURL on a google maps URL with parameters saddr and daddr wit

16条回答
  •  无人及你
    2020-12-02 04:46

    If you don't want to ask for location permissions and don't have the lat and lng, use the following.

    NSString *destinationAddress = @"Amsterdam";
    
    Class itemClass = [MKMapItem class];
    if (itemClass && [itemClass respondsToSelector:@selector(openMapsWithItems:launchOptions:)]) {
    
        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        [geocoder geocodeAddressString:destinationAddress completionHandler:^(NSArray *placemarks, NSError *error) {
            if([placemarks count] > 0) {
    
                MKPlacemark *placeMark = [[MKPlacemark alloc] initWithPlacemark:[placemarks objectAtIndex:0]];
    
                MKMapItem *mapItem = [[MKMapItem alloc]initWithPlacemark:placeMark];
    
                MKMapItem *mapItem2 = [MKMapItem mapItemForCurrentLocation];
    
    
                NSArray *mapItems = @[mapItem, mapItem2];
    
                NSDictionary *options = @{
            MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving,
            MKLaunchOptionsMapTypeKey:
                [NSNumber numberWithInteger:MKMapTypeStandard],
            MKLaunchOptionsShowsTrafficKey:@YES
                };
    
                [MKMapItem openMapsWithItems:mapItems launchOptions:options];
    
            } else {
                //error nothing found
            }
        }];
        return;
    } else {
    
        NSString *sourceAddress = [LocalizedCurrentLocation currentLocationStringForCurrentLanguage];
    
        NSString *urlToOpen = [NSString stringWithFormat:@"http://maps.google.com/maps?saddr=%@&daddr=%@",
                     [sourceAddress stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                     [destinationAddress stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlToOpen]];
    }
    

    For ios5, the Current Location needs to be in the correct language. I use the LocalizedCurrentLocation from this post http://www.martip.net/blog/localized-current-location-string-for-iphone-apps

    For ios6, I use the CLGeocoder to get the placemark and then open the map with it and the current location.

    Remember to add CoreLocation.framework and MapKit.framework

提交回复
热议问题