iphone mapview get directions - iphone

I would like to find a simple way to get directions. Is there any way to do this with mapview?
Below is my current code.
- (IBAction)goToMap:(id)sender {
[self.view addSubview:self.mapUIView];
[self.mapUIView setFrame:CGRectMake(0, 0, 320, 460)];
self.mapview.mapType = MKMapTypeStandard;
CLLocationCoordinate2D coordinate;
coordinate.latitude = [[self.find lat] floatValue];
coordinate.longitude = [[self.find lng] floatValue];
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
[annotation setCoordinate:coordinate];
[annotation setTitle:[self.find name]];
//[annotation setSubtitle:#"Hello"];
[self.mapview addAnnotation:annotation];
[annotation release];
[self zoomMapViewToFitAnnotations:self.mapview animated:YES];
}

You cannot use MapKit for driving directions. It does not support this.

If you want to show the current position of device (like while driving) you have to add CoreLocation framework in your project and should use "updateLocation" method for getting current location but if you want to draw a path between two location you have to use Google Api for this.

If you want to plot directions use:
https://github.com/kishikawakatsumi/MapKit-Route-Directions

CLLocationManager *manager = [[CLLocationManager alloc] init] ;
CLLocationCoordinate2D currentLocation = [manager location].coordinate;
CLLocationCoordinate2D coords = CLLocationCoordinate2DMake(37.365502,-94.394531);
NSString *fromLocation = [NSString stringWithFormat: #"%f,%f",
currentLocation.latitude, currentLocation.longitude];
NSString *toLocation = [NSString stringWithFormat: #"%f,%f",
Coordinate.latitude, Coordinate.longitude];
NSString *url = [NSString stringWithFormat:
#"http://maps.google.com/maps?saddr=%#&daddr=%#", fromLocation, fromLocation];
UIWebView *webView = [[UIWebView alloc]init];
NSURL *targetURL = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];

Related

Reload the Map when we navigate to MapTabBar

I have a tabBarView controller and a TableViewController. When I click on a row I wan to go to another Tab which is UIViewController with Map:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
if(storeName)
[self setMap];
}
- (void) setMap {
NSLog(#"Name:%#\n", storeName);
NSLog(#"Adress:%#\n", storeAddress);
self.indexMapView.delegate = self;
self.indexMapView.showsUserLocation = NO;
self.locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager setDistanceFilter:kCLDistanceFilterNone];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[self.indexMapView setShowsUserLocation:YES];
CLLocationCoordinate2D location = [self getLocationFromAddressString:self.storeAddress];
NSLog(#"%g", location.latitude);
MapViewAnnotation *mapAnnotation = [[MapViewAnnotation alloc] initWithTitle:#"Store location" coordinate:location];
[self.indexMapView addAnnotation:mapAnnotation];
}
-(CLLocationCoordinate2D) getLocationFromAddressString:(NSString*) addressStr {
NSLog(#"FFF");
NSString *urlStr = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv",
[addressStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSError *error = nil;
NSString *locationStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlStr] encoding:NSUTF8StringEncoding error:&error];
NSArray *items = [locationStr componentsSeparatedByString:#","];
double lat = 0.0;
double lon = 0.0;
if([items count] >= 4 && [[items objectAtIndex:0] isEqualToString:#"200"]) {
lat = [[items objectAtIndex:2] doubleValue];
lon = [[items objectAtIndex:3] doubleValue];
}
else {
NSLog(#"Address, %# not found: Error %#",addressStr, [items objectAtIndex:0]);
}
CLLocationCoordinate2D location;
location.latitude = lat;
location.longitude = lon;
return location;
}
This is how I go to the MapViewController:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
MapViewController *mapViewController = [[MapViewController alloc]init];
[mapViewController setStoreAddress:store.address];
[mapViewController setStoreName:store.name];
[mapViewController viewDidLoad];
[self.tabBarController setSelectedIndex:4];
}
The problem is Map does not get update when I go to the page again. When I tried it with PushSegue, it works. but how can I make it work with TabBar?
Well, it looks like you commented out your call to -setMap, which means that when the view loads, nothing of interest is going to happen. Was that intentional?
I figured out how can I pass the data over tab bars. You can find more descriptions in these links:
iPhone: How to Pass Data Between Several Viewcontrollers in a Tabbar App
Passing a managedObjectContext through to a UITabBarController's views
Also this tutorial is useful.

Passing coords of annotation Mapkit tapped

In my app, I have a set of location and their relative annotation. I have a button where cliking it, i go to a method that call a URL web service to get the google street view.
My code is:
- (NSString*)urlStreetview:(id<MKAnnotation>)annotation{
CLLocation *pinLocation = [[CLLocation alloc] initWithLatitude:annotation.coordinate.latitude longitude:annotation.coordinate.longitude];
NSLog(#"lat:%f",pinLocation.coordinate.latitude);
NSLog(#"lon:%f",pinLocation.coordinate.longitude);
NSString *lat_string = [[NSString alloc] initWithFormat:#"%f", pinLocation.coordinate.latitude];
NSString *lon_string = [[NSString alloc] initWithFormat:#"%f", pinLocation.coordinate.longitude];
NSString *url1 = [NSString stringWithFormat:#"http:myweb/streetview.php"];
NSString *url2 = [url1 stringByAppendingString: #"?lat="];
NSString *url3 = [url2 stringByAppendingString:lat_string];
NSString *url4 = [url3 stringByAppendingString:#"&lon="];
NSString *url = [url4 stringByAppendingString:lon_string];
NSLog(#"url:%#",url);
return url;
}
I wrote the previous method to have a url that is composed with the LatLong of the annotation.
I have a button called PressMe on the annotation pin. When I push it, I want to to excute the previous method, to calle the url, but I do not understand how pass the selected annotation to the streetView method.
- (IBAction)PressMe:(id)sender
{
UIViewController *webViewController = [[[UIViewController alloc] init] autorelease];
UIWebView *uiWebView = [[[UIWebView alloc] initWithFrame: CGRectMake(0,0,320,480)] autorelease];
[uiWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString: [self urlStreetview: ????]]]]; //HERE IS MY MY PROBLEM
[webViewController.view addSubview: uiWebView];
webViewController.title = #"web bar";
[self.navigationController pushViewController:webViewController animated:YES];
//[[self navigationController] pushViewController:thirdViewController animated:YES];
}
thanks in advance!
I am going to answer my question myself. I just resolve my problem an it work perfectly. The code allows to show a web view in order to have a steet View google service of the annotation map Kit annotation. Obviusly, as I am relatively new iphone developer,if someone wants to add/suggest/improve, he is welcome.
My button implementation:
- (IBAction)PressMe:(id)sender
{
UIViewController *webViewController = [[[UIViewController alloc] init] autorelease];
UIWebView *uiWebView = [[[UIWebView alloc] initWithFrame: CGRectMake(0,0,320,480)] autorelease];
[uiWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString: self.urlStreetview]]];
[webViewController.view addSubview: uiWebView];
webViewController.title = #"web bar";
[self.navigationController pushViewController:webViewController animated:YES];
//[[self navigationController] pushViewController:thirdViewController animated:YES];
}
With this button I call my (following) method "urlStreetview" the, with the annotation selected, composes a string in order to have a complet url with the apropriete GET php parameter. The url is the direction of my (very simple) web service that allow to call the google API street View.
- (NSString*)urlStreetview{
//there can only be one selected annotation so get the one at index 0
id<MKAnnotation> selectedAnnotation = [_mapView.selectedAnnotations objectAtIndex:0];
CLLocation *pinLocation = [[CLLocation alloc] initWithLatitude:selectedAnnotation.coordinate.latitude longitude:selectedAnnotation.coordinate.longitude];
//Now I have the annotation coordinate selected, so now I am able to compound the urladdingo to my base url:http://myurl/streetview.php, the GET part, I mean the lat lon coords:
NSString *lat_string = [[NSString alloc] initWithFormat:#"%f", pinLocation.coordinate.latitude];
NSString *lon_string = [[NSString alloc] initWithFormat:#"%f", pinLocation.coordinate.longitude];
NSString *url1 = [NSString stringWithFormat:#"http://myurl/streetview.php"];
NSString *url2 = [url1 stringByAppendingString: #"?lat="];
NSString *url3 = [url2 stringByAppendingString:lat_string];
NSString *url4 = [url3 stringByAppendingString:#"&lon="];
NSString *url = [url4 stringByAppendingString:lon_string];
NSLog(#"url:%#",url);
return url;
}
I hope It can be useful!

Tracking user location all the time algorithm for an iphone app

I'm developing an iphone app that tracks the user location all the time.
The location can be in accuracy of handerts of meters (up to 400-500). And should be updated at least once an hour (even if there is no change in user's location, I would like to keep track on it)
I would like to know what is the best way to do that.
If I use CLLocation, I would like to use startupdatinglocation once in an hour and then use startmonitoringsignificantlocationchanges. Do you think it's the best way to do that causing minimum battery drain
The other option is using a geolocation api like geoloqi but i assume that using the realtime tracking mode all the time would cause a battery drain and the passive mode is not good enough accuracy (as i understood it gives accuracy like in wich city are you)
I would be glad if someone has any idea for a recommended api i could use or an efficient algorithm to use CLLocation to solve my problem.
Thank you!
You can track the location by maintaining a variable which reads the location from the GPS software and write the algorithm using a timer that reads the location every second or whatever precision u want
Try this code I think This will be work for you.
In .h file add this code
#import "CoreLocation/CoreLocation.h"
#import "MapKit/MapKit.h"
#interface AddressAnnotation : NSObject<MKAnnotation>
{
CLLocationCoordinate2D coordinate;
NSString *mTitle;
NSString *mSubTitle;
}
#end
#interface NearestPropertyMatchViewController : UIViewController<MKMapViewDelegate> {
CLLocationManager *locationManager;
IBOutlet MKMapView *searchMap;
NSMutableArray *searchListArray;
AddressAnnotation *addAnnotation;
}
-(CLLocationCoordinate2D) addressLocation:(NSString *)str;
#property (nonatomic, retain) CLLocationManager *locationManager;
#end
In .m file add this code.
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];
NSString *latitude = [NSString stringWithFormat:#"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", coordinate.longitude];
NSLog(#"dLatitude : %#", latitude);
NSLog(#"dLongitude : %#",longitude);
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta=100;
span.longitudeDelta=100;
region.span=span;
for(int i=0;i<[regestrationArray count];i++)
{
CLLocationCoordinate2D location = [self addressLocation:[regestrationArray objectAtIndex:i]];
region.center=location;
addAnnotation = [[AddressAnnotation alloc] initWithCoordinate:location];
[searchMap addAnnotation:addAnnotation];
[searchMap setRegion:region animated:TRUE];
[searchMap regionThatFits:region];
}
-(CLLocationCoordinate2D) addressLocation :(NSString *)str
{
NSError* error = nil;
NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv",
[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
NSArray *listItems = [locationString componentsSeparatedByString:#","];
double latitude = 0.0;
double longitude = 0.0;
if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:#"200"]) {
latitude = [[listItems objectAtIndex:2] doubleValue];
longitude = [[listItems objectAtIndex:3] doubleValue];
}
else {
//Show error
}
CLLocationCoordinate2D location;
location.latitude = latitude;
location.longitude = longitude;
NSLog(#" lati=%f lon=%f",latitude,longitude);
return location;
}
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation
{
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"currentloc"];
annView.pinColor = MKPinAnnotationColorGreen;
annView.animatesDrop=TRUE;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
return annView;
}

How to update Mapview Periodically?

In my application i want to update the MapView periodically and redraw the the path on map as per new location.
Is it possible using MKMapView?
This is my didload metho for drawing and annotation on mapview.
- (void)viewDidLoad
{
NSString *url=[NSString stringWithFormat:#"xxxxx.php?uid=%#&buddy_uid=%#",UserUID,buddyUid];
NSLog(#"%#",url);
NSLog(#"%#",url);
NSString * jsonString = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:url] encoding:NSUTF8StringEncoding error:nil];
NSLog(#"return data %#",jsonString);
NSDictionary *jsonDic = [jsonString JSONValue];
buddyLocation = [[NSString alloc] initWithFormat:#"%#,%#",[jsonDic objectForKey:#"Lattitude"],[jsonDic objectForKey:#"Longitude"]];
[super viewDidLoad];
locmanager = [[CLLocationManager alloc] init];
[locmanager setDelegate:self];
[locmanager setDesiredAccuracy:kCLLocationAccuracyBest];
//[locmanager startUpdatingLocation];
MKMapView *mapnew;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
mapnew = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 768, 1004)];
}
else
{
mapnew = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
}
[mapnew setDelegate:self];
[self.view addSubview:mapnew];
MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
region.center.latitude = lat1 floatValue];//22.56574;
region.center.longitude =lng1 floatValue];//73.74575;
NSString *currentLocation = [[NSString alloc] initWithFormat:#"%#,%#",lat1,lng1];
NSLog(#"%#",currentLocation);
DisplayMap *ann = [[DisplayMap alloc] init];
ann.title = #"Current Location";
ann.coordinate = region.center;
[mapnew addAnnotation:ann];
NSLog(#"%#",jsonDic);
region.center.latitude = [[jsonDic objectForKey:#"Lattitude"] floatValue];//23.56574;
region.center.longitude = [[jsonDic objectForKey:#"Longitude"] floatValue];//72.74575;
ann = [[DisplayMap alloc] init];
ann.title = #"Buddy Location";
ann.coordinate = region.center;
[mapnew addAnnotation:ann];
KMLParser *kml = [KMLParser parseKMLAtURL:[NSURL URLWithString:[NSString
stringWithFormat:#"https://maps.google.com/maps?saddr=%#&daddr=%#&
output=kml",currentLocation,buddyLocation]]];
NSArray *overlays = [kml overlays];
[mapnew addOverlays:overlays];
MKMapRect flyTo = MKMapRectNull;
for (id <MKOverlay> overlay in overlays)
{
if (MKMapRectIsNull(flyTo))
{
flyTo = [overlay boundingMapRect];
}
else
{
flyTo = MKMapRectUnion(flyTo, [overlay boundingMapRect]);
}
}
mapnew.visibleMapRect = flyTo;
[mapnew release];
mapnew =nil;
}
}
-(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
MKPolylineView *line = [[[MKPolylineView alloc] initWithPolyline:overlay] autorelease];
line.strokeColor = [UIColor blueColor];
line.lineWidth =2.0;
return line;
}
ViewDidiLoad method is called only once when the view is loaded After that it would only give control to methods like viewWillappear etc on successive visits . What you have to do is seperate the method which parses the location data from viewDidLoad, and make it set an array or objects . And call the method to reset these contents on Map i.e. remove previous annotations or overlay and then add new ones . problem solved. You could call these method at fixed interval using timer or something like that. I guess this should help.

Bing Maps in iPhone Application

How to integrate Bing Maps into iPhone Application?
I am doing using VirtualEarthKit framework [website appears to host malware].
My code is as below :
I am getting error while getting token.
{
VECommonService *commonService = [[VECommonService alloc] init];
NSString *token;
printf("2\n");
NSError *error=[commonService getToken:&token forUserID:#"abc" password:#"def" ipAddress:#"123"];
NSString *errMsg= [error description];
printf("\n%s\n",[errMsg UTF8String]);
printf("3\n");
VEGeocodeService *geocodeService = [[VEGeocodeService alloc] init];
VEGeocodeRequest *geocodeRequest = [[VEGeocodeRequest alloc] init];
printf("4\n");
geocodeRequest.query = #"Portland State University";
geocodeRequest.token = token;
printf("5\n");
VEServiceResponse *geocodeResponse = [geocodeService geocode:geocodeRequest];
VEGeocodeResult *geocodeResult = [geocodeResponse.results objectAtIndex:0];
//NSLog([geocodeResult.location description]);
//NSLog([geocodeResult.address description]);
VEImageryService *imageryService = [[VEImageryService alloc] init];
VEGetMapURIRequest *mapRequest = [[VEGetMapURIRequest alloc] init];
mapRequest.center = geocodeResult.location;
mapRequest.token = token;
VEGetMapURIResponse *mapResponse = [imageryService getMapURI:mapRequest];
NSURL *url = mapResponse.mapURL;
//printf("\n\n URL==> %s",[url relativeString]);
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
[self.view addSubview:webView];
}
is there any way to use bing maps in an iPhone app?