Apple Map : get direction - iphone

How can I use Apple map for getting direction between two places?
I can provide the latitude and longitude of that two places?
Is it possible to show the direction in my app itself?
or Should I need to show the direction in the in built Map app of apple's iPhone?

You can send user to navigation app in iOS6 or google maps prior to iOS6.
Here's a sample code:
Class itemClass = [MKMapItem class];
if (itemClass && [itemClass respondsToSelector:#selector(openMapsWithItems:launchOptions:)]) {
// iOS 6 MKMapItem available
MKPlacemark* place = [[MKPlacemark alloc] initWithCoordinate:_targetLocation 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];
} else {
// Pre-iOS 6
CLLocationCoordinate2D coords = _lastLocation.coordinate;
NSString *stringURL = [NSString stringWithFormat:#"http://maps.google.com/maps?saddr=%g,%g&daddr=%g,%g", coords.latitude, coords.longitude, _targetLocation.latitude, _targetLocation.longitude];
NSURL *url = [NSURL URLWithString:stringURL];
[[UIApplication sharedApplication] openURL:url];
}

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];

Related

Search nearby in iOS Maps

I am trying to build a simple application using MapKit that will automatically search for a specific place when the app launches and drop pin(s) on the map at the locations(s). I am seeing all sorts of ways to load locations (lat/lon, etc), but nothing that lets me search for a specific business name, restaurant name, etc.
I am expecting to work with Apple Maps. However, if Google Maps would be a better solve than so be it.
Any help would be appreciated. Thanks
iOS >= 6.1 provides MKLocalSearch, MKLocalSearchRequest to search for natural language points of interest. Sample
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
request.region = regionToSearchIn;
request.naturalLanguageQuery = #"restaurants"; // or business name
MKLocalSearch *localSearch = [[MKLocalSearch alloc] initWithRequest:request];
[localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
// do something with the results / error
}];
i know its late but hope this helps!
[super viewDidLoad];
[self.searchDisplayController setDelegate:self];
[self.ibSearchBar setDelegate:self];
self.ibMapView.delegate=self;
// Zoom the map to current location.
[self.ibMapView setShowsUserLocation:YES];
[self.ibMapView setUserInteractionEnabled:YES];
[self.ibMapView setUserTrackingMode:MKUserTrackingModeFollow];
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate=self;
[locationManager startUpdatingLocation];
[self.ibMapView setRegion:MKCoordinateRegionMake(locationManager.location.coordinate, MKCoordinateSpanMake(0.2, 0.2))];
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
request.region = self.ibMapView.region;
request.naturalLanguageQuery = #"restaurant";
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
localSearch = [[MKLocalSearch alloc] initWithRequest:request];
[localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error){
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
results = response;
if (response.mapItems.count == 0)
NSLog(#"No Matches");
else
for (MKMapItem *item in response.mapItems)
{
NSLog(#"name = %#", item.name);
NSLog(#"Phone = %#", item.phoneNumber);
[_matchingItems addObject:item];
MKPointAnnotation *annotation =
[[MKPointAnnotation alloc]init];
annotation.coordinate = item.placemark.coordinate;
annotation.title = item.name;
[self.ibMapView addAnnotation:annotation];
}
}];
}
Make the following steps to display nearest places.
Using google API find the Nearest Places Google Places API
The google API provide LAt and Long and address Informations.
Then Store the LAt and Long Values to Array then USing this lat and long values you can display Annotations in Apple map (iOS 6+) and Google Map (iOS 5).

iOS UIActivity View Controller: Add To Reading List Button?

Is there a service to be able to add a URL to the iOS Safari's Reading List from in a app.
I would have a url to add and a UIWebView,but I have researched and I can't find anything.
Here is my working UIActivityViewController.
-(IBAction)actionButton:(id)sender;{
NSLog(#"shareButton pressed");
NSURL *URL = [NSURL URLWithString:self.feedItem[#"url"]];//this is your text string
NSArray *activityItems = #[URL];
ARChromeActivity *chromeActivity = [[ARChromeActivity alloc] init];
TUSafariActivity *TUSafari = [[TUSafariActivity alloc] init];
MLCruxActivity *cruxActivity = [[MLCruxActivity alloc] init];
NSArray *applicationActivities = [NSArray arrayWithObjects:TUSafari,chromeActivity,cruxActivity, nil];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities: applicationActivities];
activityVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:applicationActivities];
activityVC.excludedActivityTypes = #[UIActivityTypeAssignToContact];
[self presentViewController:activityVC animated:TRUE completion:nil];
}
UPDATE: iOS 7 added an API to accomplish this:
#import <SafariServices/SafariServices.h>
SSReadingList * readList = [SSReadingList defaultReadingList];
NSError * error = [NSError new];
BOOL status =[readList addReadingListItemWithURL:[NSURL URLWithString:urlToAdd] title:titleToAdd previewText:previewText error:&error];
if(status)
{
NSLog(#"Added URL");
}
else NSLog(#"Error");
Currently (iOS SDK 6.1) there is no way to add a item to the Reading List from a third party app.
There are some alternatives like Readability you could use.

How to draw routes on maps in ios 6?

I want to show maps & draw routes on maps. My application supports for ios 4 plus. So how should i use maps to work on ios 6 as well as before. Also i want to know sholud i use custom mapview in my app to display maps & routes or should i use
[[UIApplication sharedApplication] openURL:]
I have never user MapKits. So please provide if any tutorial. Also let me know if there are any rd party libraries that can be used.
If you don't want an in-app map. 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]];
}
This opens the map application and checks if it is ios5 or ios6.
For ios5 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
I think this'll help you:
http://developer.decarta.com/Apis/IOS/Tutorial/Lesson6
http://developer.decarta.com/Apis/IOS/Tutorial/Lesson6Example
Or this?
http://spitzkoff.com/craig/?p=136
Maybe this is fun to do if you want data in your map:
http://www.raywenderlich.com/21365/introduction-to-mapkit-in-ios-6-tutorial
Or some basic information about Mapkit
http://www.techotopia.com/index.php/Working_with_Maps_on_the_iPhone_with_MapKit_and_the_MKMapView_Class

Xcode iOS 4.2.1 -> Give Map View the address to show the pin? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Forward Geocode Example using CLGeocoder
I have a plist full of names and their adrresses. I want my iOS app to show on a map view a pin with the address of the person he has selected. Can I import the address to map view and get a pin? And how?? Thank you.
Use the CLGeocoder class to convert addresses into lat/long coordinates:
Forward Geocode Example using CLGeocoder
The more accurate address you have, the better the result should be so with exact addresses you should get very accurate points.
Another option is to use Google's geocoding web service, simply pass the address string to this function and you will get an CLLocationCoordinate2D which contains a latitude & longitude.
Right now it grabs the location at the 0th index, which is the closest matching result. Log out the result to see the JSON response from Google.
- (CLLocationCoordinate2D) geoCodeUsingAddress:(NSString *)address
{
NSString *esc_addr = [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *req = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?sensor=true&address=%#", esc_addr];
CLLocationCoordinate2D center;
NSString *result = [NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:NULL];
if (result)
{
//NSLog(#"LOC RESULT: %#", result);
NSError *e;
NSDictionary *resultDict = [NSJSONSerialization JSONObjectWithData: [result dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &e];
NSArray *resultsArray = [resultDict objectForKey:#"results"];
if(resultsArray.count > 0)
{
resultDict = [[resultsArray objectAtIndex:0] objectForKey:#"geometry"];
resultDict = [resultDict objectForKey:#"location"];
center.latitude = [[resultDict objectForKey:#"lat"] floatValue];
center.longitude = [[resultDict objectForKey:#"lng"] floatValue];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Results Found" message:#"No locations were found using, please try again." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
//goes through each result
/*for(NSDictionary *dict in resultsArray)
{
resultDict = [dict objectForKey:#"geometry"];
resultDict = [resultDict objectForKey:#"location"];
}*/
}
return center;
}
This is whats known as Forward Geocoding, and there is no built in API to do this for you. You need to use an external service, which one you use really depends on your app.
I have used Google's service for this. http://code.google.com/apis/maps/documentation/geocoding/
It is a very simple API, but has restrictions based on your app's license. I know there are a couple other services for this, but I'll leave that as an exercise to you.

Send user location coordinates to SMS.app as an googleMaps-link

I wanna send my location coordinates as a Google Maps link (http://maps.google.com/?saddr=%1.6f,%1.6f) as an SMS but i just can't get it to work... How should I do so that the GoogleMaps-link varies to my location??
MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];
controller.body = #"This is my location http://maps.google.com/?saddr=%1.6f,%1.6f";
NSString *googleMaps = [NSString stringWithFormat:#"http://maps.google.com/?saddr=%1.6f,%1.6f", location.latitude, location.longitude];
controller.recipients = [NSArray arrayWithObjects:nil];
controller.messageComposeDelegate = self;
[self presentModalViewController:controller animated:YES];
}
}
Any ideas? Would really appreciate an answer!!!!
Thanks you and happy holidays!
shouldn't you have:
controller.body = [NSString stringWithFormat:#"http://maps.google.com/?saddr=%1.6f,%1.6f", location.latitude, location.longitude];
you're hard coding the body and then creating an unrelated string which is probably properly formatted and never doing anything with it.
you need to do location.coordinate.latitude, location.coordinate.longitude assuming location is a cllocation object.