get direction functionality on map app iOS - ios

I want to implement get direction functionality between two locations in iOS default Map App and I've tried this
Class itemClass = [MKMapItem class];
if (itemClass && [itemClass respondsToSelector:#selector(openMapsWithItems:launchOptions:)]) {
// Use iOS 6 maps
NSString *latString = #"23.0300";
NSString *longString = #"72.5800";
CLLocationCoordinate2D ctrpoint;
ctrpoint.latitude = [latString doubleValue];
ctrpoint.longitude = [longString doubleValue];
MKPlacemark *placemark2 = [[MKPlacemark alloc] initWithCoordinate:ctrpoint addressDictionary:nil];
MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark2];
[mapItem openInMapsWithLaunchOptions:nil];
}
But it shows the directional error as below:
I even opened the map app, located my current location, added one pin on the map nearest to my location, and get direction is still not working on that.
Also "In short Get Direction is not working completely even in native app" Can any one help me to achieve this?

Apple Maps do not support directions in India.
You could use Google Maps for directions, if its available on the phone.
If Google Maps App is not available resort to Apple maps.
Following code block might be of some help.
NSURL *appUrl;
//Is Google Maps App Installed ?
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:#"comgooglemaps://"]]) {
// Use Google Maps App to get Directions
appUrl = [NSURL URLWithString:[NSString stringWithFormat:#"comgooglemaps://?daddr=%f,%f&saddr=%f,%f",
destLocation.coordinate.latitude, destLocation.coordinate.longitude,
_currentLocation.coordinate.latitude,_currentLocation.coordinate.longitude]];
}
// Google Maps not Installed
else {
// Use Apple Maps App to get Directions
appUrl = [NSURL URLWithString:[NSString stringWithFormat:#"http://maps.apple.com/?daddr=%f,%f&saddr=%f,%f",
destLocation.coordinate.latitude, destLocation.coordinate.longitude,
_currentLocation.coordinate.latitude,_currentLocation.coordinate.longitude]];
}
[[UIApplication sharedApplication] openURL:appUrl];

According to this Apple feature availability, directions are not supported in India.
Same thing seems to go for iOS 6, according to this post.

Related

Can we launch a "link" in iMessage app?

I've got an iMessage app where basically I want to display a button and when pressed, launch another app like Safari or Maps etc.
I've tried:
if UIApplication.shared.canOpenURL(url){
but "UIApplication.shared" is only available in the main iOS app. Mine is an iMessage only app.
Any suggestions?
You can use the extensionContext property inside your MSMessagesAppViewController subclass to open URL like so:
NSURL *url = [NSURL URLWithString:#"https://www.apple.com/"];
[self.extensionContext openURL:url completionHandler:nil];
I haven't tested this, but I use this method to launch my iOS application from my iMessage extension app using custom url scheme. I've also used this to launch the AppStore from my iMessage extension.
Update:
Since you said you just want to open Maps, you could try this:
#import <MapKit/MapKit.h>
- (void)openMaps {
CLLocationCoordinate2D coordinates = CLLocationCoordinate2DMake(33.651092f, -117.744250f); // coordinates of your desired location
MKCoordinateRegion regionSpan = MKCoordinateRegionMakeWithDistance(coordinates, 5000, 5000); // 5000 is the distance in meters
NSDictionary *options = #{MKLaunchOptionsMapCenterKey: [NSValue valueWithMKCoordinate:regionSpan.center],
MKLaunchOptionsMapSpanKey: [NSValue valueWithMKCoordinateSpan:regionSpan.span]};
MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:coordinates addressDictionary:nil];
MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
[mapItem setName:#"Irvine Spectrum Center"];
[mapItem openInMapsWithLaunchOptions:options];
}
Let me know if that works out for you.

Adding a label to Destination Address when opening Apple Maps

What I want to do is allow the user to open Apple Maps and have it automatically open the Directions form for them to get directions to my location.
The destination is a Latitude/Longitude pair. I am doing this:
NSString *addressString = #"http://maps.apple.com/?daddr=50.894967,4.341626&dirflg=d";
NSURL *url = [NSURL URLWithString:addressString];
[[UIApplication sharedApplication] openURL:url];
This opens Apple Maps as I expect. However, in the destination field, it shows the Latitude/Longitude pair. I would like to specify this label. Here is what I mean:
Is there anyway I can replace the coordinates with a label using URL params?
Thanks!
You can use Core Location to get the current location and after you can set your "Start" point with that info. You don't have to set "End" point.
Please check this link, I'm sure you'll find its useful;
How to invoke iPhone Maps for Directions with Current Location as Start Address
This might not be the way you want. But it give us more flexibility to open the Map app. That is using [MKMapItem openMapsWithItems:launchOptions:] to ask the Map to open the address. The screen looks a bit different from what you might expect though.
CLLocation* location = [[CLLocation alloc] initWithLatitude:50.894967 longitude:4.341626];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(location.coordinate, 10000, 10000);
NSDictionary *addressDict = #{
(NSString *) kABPersonAddressStreetKey : #"Any Name",
};
MKPlacemark *destinationPlacemark = [[MKPlacemark alloc] initWithCoordinate:location.coordinate addressDictionary:addressDict];
MKMapItem *destinationMapItem = [[MKMapItem alloc] initWithPlacemark:destinationPlacemark];
[destinationMapItem openInMapsWithLaunchOptions:#{MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving}];
[MKMapItem openMapsWithItems:#[destinationMapItem]
launchOptions:#{
MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving,
MKLaunchOptionsMapSpanKey : [NSValue valueWithMKCoordinateSpan:region.span]
}
];
Just use core location for current location, and start, no end needed though

ios navigation with apple or google maps with several targets

i can open the apple maps application from my app to calculate a route from the current location to my placemark and it works fine.
but now i have a list of several placemarks in a given order and would like to send them to the maps application to be used as targets in between along a route from first to last placemark. is this possible?
i could as an alternative start google maps on safari which allows to set multiple targets in the url:
https://maps.google.com/maps?saddr=first&daddr=second&daddr=third+to:final&hl=en
i used the code below and it worked fine for several months but now the new online version of google maps doesn't support multiple targets requested like this anymore.
therefore you need to adjust your url like this:
https://www.google.com/maps/dir/longitude,latitude/longitude,latitude
here you can find some more information about the url search:
http://gearside.com/easily-link-to-locations-and-directions-using-the-new-google-maps/
my current solution is opening google maps on safari with the link, where i add +to: targets in between:
for (int i == 0; int i < route.count; i++) {
if (i == 0) {
NSString *start = [NSString stringWithFormat:#"http://maps.google.com/maps?saddr=%f,%f", latitude, longitude];
locationString = start;
}
if (i != 0 && i != route.count - 1) {
NSString *between = [NSString stringWithFormat:#"+to:%f,%f", latitude, longitude];
locationString = [locationString stringByAppendingString:between];
}
if (i == route.count - 1) {
NSString *end = [NSString stringWithFormat:#"&daddr=%f,%f", latitude, longitude];
NSString *type = #"&dirflg=w";
locationString = [locationString stringByAppendingString:end];
locationString = [locationString stringByAppendingString:type];
}
}
NSURL *url = [NSURL URLWithString:locationString];
[[UIApplication sharedApplication] openURL:url];
this works fine if I'm using the iOS 5 or 6 sSimulator which opens the link in Safari on the mobile version of maps.google.com
but when i run it on an iOS 5 device and probably on an iOS6 device with installed Google Maps the link starts in Google Maps and there the route is drawn wrong (especially with many targets) and the targets in between have no annotations...
anybody got an idea how to force a link beeing opened in Safari?

How to open Maps Application from other Application in iPhone SDK

Why when I'm opening
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"http://maps.google.com/maps?saddr=Current Location&daddr=123 Main St,Ottawa,ON"]];
Maps application isn't opening? Moreover, even Safari isn't opening.
But when I opening: http://google.com, Safari is normally opening.
Well... As this question over 2 years old and has received over 3k views without an answer I think it's about time someone posts one. Mainly because obviously traffic keeps appearing here.
In anycase you can find the answer in various other parts of this site but the one that worked like a charm for me is this one: https://stackoverflow.com/a/12432512/525576
The great part of this answer is it address iOS 5 and below and iOS 6 and above.
I've edited the answer a bit to fit arc standards that automatically come with iOS 7.
CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude,longitude);
//create MKMapItem out of coordinates
MKPlacemark* placeMark = [[MKPlacemark alloc] initWithCoordinate:coordinate addressDictionary:nil];
MKMapItem* destination = [[MKMapItem alloc] initWithPlacemark:placeMark];
if([destination respondsToSelector:#selector(openInMapsWithLaunchOptions:)])
{
//using iOS6 native maps app
[destination openInMapsWithLaunchOptions:#{MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving}];
}
else
{
//using iOS 5 which has the Google Maps application
NSString* url = [NSString stringWithFormat: #"http://maps.google.com/maps?saddr=Current+Location&daddr=%f,%f", latitude, longitude];
[[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];
}

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

I know it's possible to start the iPhone maps application by calling openURL on a google maps URL with parameters saddr and daddr with location strings or Lat/Long (see example below).
But I'm wondering if it's possible to make the start address be the "Current Location" maps bookmark so that I can use the Maps app's location handling code. My Google search has been pretty fruitless.
For example:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat: #"http://maps.google.com/maps?saddr=%#&daddr=%#", myLatLong, latlong]]];
Except with something to invoke the current location bookmark in place of myLatLong.
Pre iOS 6
You need to use Core Location to get the current location, but with that lat/long pair, you can get Maps to route you from there, to a street address or location. Like so:
CLLocationCoordinate2D currentLocation = [self getCurrentLocation];
// this uses an address for the destination. can use lat/long, too with %f,%f format
NSString* address = #"123 Main St., New York, NY, 10001";
NSString* url = [NSString stringWithFormat: #"http://maps.google.com/maps?saddr=%f,%f&daddr=%#",
currentLocation.latitude, currentLocation.longitude,
[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];
Finally, if you do want to avoid using CoreLocation to explicitly find the current location, and want to use the #"http://maps.google.com/maps?saddr=Current+Location&daddr=%#" url instead, then see this link that I provided in comments below for how to localize the Current+Location string. However, you are taking advantage of another undocumented feature, and as Jason McCreary points out below, it may not work reliably in future releases.
Update for iOS 6
Originally, Maps used Google maps, but now, Apple and Google have separate maps apps.
1) If you wish to route using the Google Maps app, use the comgooglemaps URL scheme:
NSString* url = [NSString stringWithFormat: #"comgooglemaps://?daddr=%#&directionsmode=driving",
[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
BOOL opened = [[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];
2) To use Apple Maps, you can use the new MKMapItem class for iOS 6. See the Apple API docs here
Basically, you will use something like this, if routing to destination coordinates (latlong):
MKPlacemark* place = [[MKPlacemark alloc] initWithCoordinate: latlong addressDictionary: nil];
MKMapItem* destination = [[MKMapItem alloc] initWithPlacemark: place];
destination.name = #"Name Here!";
NSArray* items = [[NSArray alloc] initWithObjects: destination, nil];
NSDictionary* options = [[NSDictionary alloc] initWithObjectsAndKeys:
MKLaunchOptionsDirectionsModeDriving,
MKLaunchOptionsDirectionsModeKey, nil];
[MKMapItem openMapsWithItems: items launchOptions: options];
In order to support both iOS 6+ and pre iOS 6 in the same code, I'd recommend using something like this code that Apple has on the MKMapItem API doc page:
Class itemClass = [MKMapItem class];
if (itemClass && [itemClass respondsToSelector:#selector(openMapsWithItems:launchOptions:)]) {
// iOS 6 MKMapItem available
} else {
// use pre iOS 6 technique
}
This would assume that your Xcode Base SDK is iOS 6 (or Latest iOS).
NSString* addr = [NSString stringWithFormat:#"http://maps.google.com/maps?daddr=Current Location&saddr=%#",startAddr];
NSURL* url = [[NSURL alloc] initWithString:[addr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[[UIApplication sharedApplication] openURL:url];
[url release];
This works but only when the iPhone/iPod language is set in English. If you want to support other languages you'll have to use a localized string to match the Maps bookmark name.
This works on iPhone:
http://maps.google.com/maps?saddr=Current Location&daddr=123 Main St,Ottawa,ON
You can use a preprocessor #define like:
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
to understand your iOS version. Then, I can use this code to support iOS 6, too:
NSString* addr = nil;
if (SYSTEM_VERSION_LESS_THAN(#"6.0")) {
addr = [NSString stringWithFormat:#"http://maps.google.com/maps?daddr=%1.6f,%1.6f&saddr=Posizione attuale", view.annotation.coordinate.latitude,view.annotation.coordinate.longitude];
} else {
addr = [NSString stringWithFormat:#"http://maps.apple.com/maps?daddr=%1.6f,%1.6f&saddr=Posizione attuale", view.annotation.coordinate.latitude,view.annotation.coordinate.longitude];
}
NSURL* url = [[NSURL alloc] initWithString:[addr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[[UIApplication sharedApplication] openURL:url];
Because of sandboxing, you don't have access to the Map application's bookmarks.
Instead, use Core Location to determine the current location yourself. Then use that location (the lat and long) in the URL you build to open Maps.
I recommend checking out CMMapLauncher, a mini-library that I built to launch Apple, Google, and other iOS mapping apps with a specific mapping request. With CMMapLauncher, the code to get the directions in your question would be:
[CMMapLauncher launchMapApp:CMMapAppAppleMaps
forDirectionsFrom:[CMMapPoint mapPointWithName:#"Origin"
coordinate:myLatLong]
to:[CMMapPoint mapPointWithName:#"Destination"
coordinate:latlong]];
As you can see, it also encapsulates the version checking required between iOS 6 & others.
Hey since iOS6 is out!
Apple did something remarkable in a bad way (from my point of view).
Apple's maps are launched and for devices running iOS 6 you should not use maps.google.com/?q= if you want the iDevice to open the native Plan app. Now it would be maps.apple.com/?q=.
So that developers don't have to much work, the friendly maps.apple.com server redirects all non-Apple devices to maps.google.com so the change is transparent.
This way we developpers just have to switch all google query strings to apple ones.
This is what I dislike a lot.
I had to implement that functionnality today so I did it. But I felt I should not just rewrite every url lying in mobile website to target Apple's maps server so I thought I'd just detect iDevices server-side and serve apple urls just for those. I thought I'd share.
I'm using PHP so I used the opensource Mobile Detect library : http://code.google.com/p/php-mobile-detect/
Just use the isiPad pseudo method as a boolean getter and you're done, you wont convert google into apple ;-)
$server=$detect->isiPad()?"apple":"google";
$href="http://maps.{$server}.com/?q=..."
Cheers!
You can do this now in html just from a url on your mobile device only. Here's an example. The cool thing is if you turn this into a qr code you have a way of someone getting directions to you from wherever they are just by scanning it on their phone.
The real solution can be found here. Z5 Concepts iOS Development Code Snippet
It just requires a little bit of encoding.
- (IBAction)directions1_click:(id)sender
{
NSString* address = #"118 Your Address., City, State, ZIPCODE";
NSString* currentLocation = #"Current Location";
NSString* url = [NSStringstringWithFormat: #"http://maps.google.com/maps?saddr=%#&daddr=%#",[currentLocation stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
UIApplication *app = [UIApplicationsharedApplication];
[app openURL: [NSURL URLWithString: url]];
}
For iOS6 the apple docs recommend using the equivalent maps.apple.com URL Scheme
so use
http://maps.apple.com/maps?saddr=%f,%f&daddr=%f,%f
instead of
http://maps.google.com/maps?saddr=%f,%f&daddr=%f,%f
to be backwards compatible the code would be
NSString* versionNum = [[UIDevice currentDevice] systemVersion];
NSString *nativeMapScheme = #"maps.apple.com";
if ([versionNum compare:#"6.0" options:NSNumericSearch] == NSOrderedAscending)
nativeMapScheme = #"maps.google.com";
}
NSString* url = [NSString stringWithFormat: #"http://%#/maps?saddr=%f,%f&daddr=%f,%f", nativeMapScheme
startCoordinate.latitude, startCoordinate.longitude,
endCoordinate.latitude, endCoordinate.longitude];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
there is a whole load of other supported parameters for the Apple Maps URL scheme : Apple URL Scheme Reference
you can use these iOS version detection macros if you have conditional code in other parts of your code. iOS version macros
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
For iOS6 Maps App, you can just use the same URL posted above
http://maps.google.com/maps?saddr=%f,%f&daddr=%#
but instead of the Google maps URL, you use the url with maps:// resulting in the following URL: maps://saddr=%f,%f&daddr=%#.
Using 'Current Location' doesn't seem to work, so I stayed with the coordinates.
Antother good thing: It's backwards compatible: On iOS5, it launches the Google Maps app.
With the current version of Google Maps, simply omit the sadr parameter:
saddr: … If the value is left blank, then the user’s current location will be used.
https://developers.google.com/maps/documentation/ios/urlscheme
My suggestion would be using OpenInGoogleMaps-iOS as this is an up to date choice (by November 2015), it supports cocoa pods installation and you are ready to go in a few clicks.
Install using: pod "OpenInGoogleMaps"
Require in header file using: #import "OpenInGoogleMapsController.h"
Sample code below:
/*In case the user does NOT have google maps, then apple maps shall open*/
[OpenInGoogleMapsController sharedInstance].fallbackStrategy = kGoogleMapsFallbackAppleMaps;
/*Set the coordinates*/
GoogleMapDefinition *definition = [[GoogleMapDefinition alloc] init];
CLLocationCoordinate2D metsovoMuseumCoords; //coordinates struct
metsovoMuseumCoords.latitude = 39.770598;
metsovoMuseumCoords.longitude = 21.183215;
definition.zoomLevel = 20;
definition.center = metsovoMuseumCoords; //this will be the center of the map
/*and here we open the map*/
[[OpenInGoogleMapsController sharedInstance] openMap:definition];
I answered this on a different thread. (Current Location doesn't work with Apple Maps IOS 6). You need to get the coordinates of the current location first, then use it to create the map url.
If you don't provide source location, it will take current location as source. Try below code-
let urlString = "http://maps.apple.com/maps?daddr=(destinationLocation.latitude),(destinationLocation.longitude)&dirflg=d"
}
UIApplication.shared.openURL(URL(string: urlString)!)

Resources