Memory leak using location manager - iphone

I use the location manager with "didUpdateToLocation". I have a memory leak that I cannot explain:
- (void) locationManager:(CLLocationManager *) manager didUpdateToLocation:(CLLocation *) newLocation
fromLocation:(CLLocation *) oldLocation {
[newLocation retain];
NSString *lCoordinates = [[NSString alloc] initWithFormat:#"%f,%f",newLocation.coordinate.latitude,newLocation.coordinate.longitude];//Memory leak here!!!
[self setLocationCoordinates:lCoordinates];
[lCoordinates release];
NSString *lat = [[NSString alloc] initWithFormat:#"%f,%f", newLocation.coordinate.latitude,newLocation.coordinate.longitude];
[lm stopUpdatingLocation];
NSMutableString *s = [[NSMutableString alloc]initWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json?location=%#&radius=10&sensor=true&key=---MyKey---", lat];
NSLog(s);
id delegate = self;
AsyncConnectionController * connectionController = [[[AsyncConnectionController alloc] initWithDelegate:delegate
selSucceeded:#selector(currentLocationConnectionSucceeded:)
selFailed:#selector(currentLocationconnectionFailed:)] autorelease];
NSURL *url = [[NSURL alloc] initWithString:s];
[connectionController startRequestForURL:url];
[lat release];
[s release];
[url release];
[newLocation release];
}
Thanks all for your help!!!

You should be able to reduce your code substantially just by using convenience methods (makes it more readable as well):
- (void) locationManager:(CLLocationManager *) manager didUpdateToLocation:(CLLocation *) newLocation fromLocation:(CLLocation *) oldLocation {
NSString *lCoordinates = [NSString stringWithFormat:#"%f,%f",newLocation.coordinate.latitude,newLocation.coordinate.longitude];
[self setLocationCoordinates:lCoordinates];
NSString *lat = [NSString stringWithFormat:#"%f,%f", newLocation.coordinate.latitude,newLocation.coordinate.longitude];
[lm stopUpdatingLocation];
NSString *s = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json?location=%#&radius=10&sensor=true&key=---MyKey---", lat];
NSLog(s);
AsyncConnectionController * connectionController = [[[AsyncConnectionController alloc] initWithDelegate:self
selSucceeded:#selector(currentLocationConnectionSucceeded:)
selFailed:#selector(currentLocationconnectionFailed:)] autorelease];
NSURL *url = [NSURL urlWithString:s];
[connectionController startRequestForURL:url];
}
OP specifies that connectionController is autorelease.

Related

Location Services permission don't get saved iOS

I have problem with the localization API in Core Location Services. I get the promt that request permission to the location services. If I click Allow and goes to Settings I can see that my app don't have permission.
This is my code in my GeoUtility class:
CLGeocoder *reverseGeocoder = [[CLGeocoder alloc] init];
CLLocationManager *lm = [[CLLocationManager alloc] init];
[lm setPurpose:#"Need to verify your region"];
[lm startUpdatingLocation];
It's trigged by a viewController in the viewDidAppear
I also have added location-services under Required Devices Capabilites in my plist file.
Add CoreLocation.framework and MapKit.framework
And
in .h
#import <MapKit/MapKit.h>
CLLocationManager *locationManager;
CLGeocoder *geocoder;
in view did load
- (void)viewDidLoad
{
locationManager = [[CLLocationManager alloc] init];
geocoder = [[CLGeocoder alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
then
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
LongitudeLbl.text = [NSString stringWithFormat:#"%.8f",currentLocation.coordinate.longitude];
LatitudeLbl.text = [NSString stringWithFormat:#"%.8f",currentLocation.coordinate.latitude];
}
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
NSString *addresstemp2 = [[NSString alloc] init];
NSString *subThoroughfare2 = [NSString stringWithFormat:#"%#",placemark.subThoroughfare];
NSString *thoroughfare2 = [NSString stringWithFormat:#"%#",placemark.thoroughfare];
NSString *postalCode2 = [NSString stringWithFormat:#"%#",placemark.postalCode];
NSString *locality2 = [NSString stringWithFormat:#"%#",placemark.locality];
NSString *administrativeArea2 = [NSString stringWithFormat:#"%#",placemark.administrativeArea];
NSString *country2 = [NSString stringWithFormat:#"%#",placemark.country];
if (![subThoroughfare2 isEqualToString:#"(null)"]) {
addresstemp2 = [NSString stringWithFormat:#"%#",subThoroughfare2];
}
if (![thoroughfare2 isEqualToString:#"(null)"]) {
addresstemp2 = [NSString stringWithFormat:#"%# %# \n",addresstemp2,thoroughfare2];
}
if (![postalCode2 isEqualToString:#"(null)"]) {
addresstemp2 = [NSString stringWithFormat:#"%# %#",addresstemp2,postalCode2];
}
if (![locality2 isEqualToString:#"(null)"]) {
addresstemp2 = [NSString stringWithFormat:#"%# %# \n",addresstemp2,locality2];
}
if (![administrativeArea2 isEqualToString:#"(null)"]) {
addresstemp2 = [NSString stringWithFormat:#"%# %# \n",addresstemp2,administrativeArea2];
}
if (![country2 isEqualToString:#"(null)"]) {
addresstemp2 = [NSString stringWithFormat:#"%# %#",addresstemp2,country2];
}
AddressLbl.text = [[NSString alloc] initWithString:addresstemp2];
[AddressLbl sizeToFit];
[locationManager stopUpdatingLocation];
} else {
}
} ];
}
And you also change setting in your Simulator GO TO THE setting and choose Location Service change it to ON. see down is your application name if it is off then change to ON

How to get device location name in iPhone?

Currently i am working in iPhone application, Using CLLocationManager to get Latitude and Longitude values fine.
I didn't know this? How to get the device location (Address) name from this latitude and longitude value? please help me
Thanks in Advance
I tried this:
- (void)viewDidLoad
{
[super viewDidLoad];
LocationManager = [[CLLocationManager alloc]init];
LocationManager.delegate=self;
LocationManager.desiredAccuracy = kCLLocationAccuracyBest;
[LocationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSString * latitude = [[[NSString alloc] initWithFormat:#"%f", newLocation.coordinate.latitude]autorelease];
NSString * longitude = [[[NSString alloc] initWithFormat:#"%f", newLocation.coordinate.longitude]autorelease];
[LocationManager stopUpdatingLocation];
NSLog(#"latitude:%#",latitude);
NSLog(#"longitude:%#",longitude);
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
[manager stopUpdatingLocation];
lati = [[NSString alloc] initWithFormat:#"%+.6f", newLocation.coordinate.latitude];
NSLog(#"address:%#",lati);
longi = [[NSString alloc] initWithFormat:#"%+.6f", newLocation.coordinate.longitude];
NSLog(#"address:%#",longi);
[geoCoder reverseGeocodeLocation: newLocation completionHandler: ^(NSArray *placemarks, NSError *error)
{
//Get nearby address
CLPlacemark *placemark = [placemarks objectAtIndex:0];
//String to hold address
NSString *locatedAt = [[placemark.addressDictionary valueForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
//Print the location to console
NSLog(#"I am currently at %#",locatedAt);
address = [[NSString alloc]initWithString:locatedAt];
NSLog(#"address:%#",address);
}];
}
CLGeocoder *ceo = [[CLGeocoder alloc]init];
CLLocation *loc = [[CLLocation alloc]initWithLatitude:32.00 longitude:21.322];
[ceo reverseGeocodeLocation: loc completionHandler:
^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(#"placemark %#",placemark);
//String to hold address
NSString *locatedAt = [[placemark.addressDictionary valueForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
NSLog(#"addressDictionary %#", placemark.addressDictionary);
NSLog(#"placemark %#",placemark.region);
NSLog(#"placemark %#",placemark.country); // Give Country Name
NSLog(#"placemark %#",placemark.locality); // Extract the city name
NSLog(#"location %#",placemark.name);
NSLog(#"location %#",placemark.ocean);
NSLog(#"location %#",placemark.postalCode);
NSLog(#"location %#",placemark.subLocality);
NSLog(#"location %#",placemark.location);
//Print the location to console
NSLog(#"I am currently at %#",locatedAt);
}];
You have ta make some reverse location. You're lucky : Apple provides a class to do that.
See CLGeocoder (for iOS >= 5.0) or MKReverseGeocoder (for iOS < 5.0)
You can use Google Maps API for this (works on any iOS):
NSString *req = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?latlng=%.5f,%.5f&sensor=false&language=da", location.latitude, location.longitude];
NSString *resultString = [NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:NULL];
Then you can parse this response to NSDictionary using Any JSON library (SBJSON in this case):
SBJSON *jsonObject = [[SBJSON alloc] init];
NSError *error = nil;
NSDictionary *response = [jsonObject objectWithString:resultString error:&error];
[jsonObject release];
Extracting address:
if (error) {
NSLog(#"Error parsing response string to NSObject: %#",[error localizedDescription]);
}else{
NSString *status = [response valueForKey:#"status"];
if ([status isEqualToString:#"OK"]) {
NSArray *results = [response objectForKey:#"results"];
int count = [results count];
//NSSLog(#"Matches: %i", count);
if (count > 0) {
NSDictionary *result = [results objectAtIndex:0];
NSString *address = [result valueForKey:#"formatted_address"];
}
}
}
You have to create a CLLocation object and pass that on to reverseGeoCoder.
Before iOS 5.0 we have MKReverse Geo-coder class to find this..Now it is deprecated..
We have to use CLGeocoder class in Core Location Framework

Reload JSON Feed within a UIView

I have a mapView that has annotation added through JSON (feed is stored in NSDictionary). Everything works great, but I want to add a feature.
I want the mapView to reload all of the annotations each time the view reappears (every time the tab bar is pressed). T've tried putting the part where the JSON is added to the NSDictionary in viewWillAppear {} .... but it does not work.
My code is below. Thanks in advance!
#import "MapViewController.h"
#import "DisplayMap.h"
#import "JSON/JSON.h"
#implementation MapViewController
#synthesize mapView;
#synthesize selectedType;
#synthesize locationManager;
// JSON from Server Actions
- (NSString *)stringWithUrl:(NSURL *)url {
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Fetch the JSON response
NSData *urlData;
NSURLResponse *response;
NSError *error;
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
// Construct a String around the Data from the response
return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
}
- (id)objectWithUrl:(NSURL *)url {
SBJsonParser *jsonParser = [SBJsonParser new];
NSString *jsonString = [self stringWithUrl:url];
// Parse the JSON into an Object
return [jsonParser objectWithString:jsonString error:NULL];
}
- (NSDictionary *) downloadFeed {
id response = [self objectWithUrl:[NSURL URLWithString:#"http://www.example.com/JSON"]];
NSDictionary *feed = (NSDictionary *)response;
return feed;
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[locationManager startUpdatingLocation];
mapView.mapType = MKMapTypeStandard;
mapView.zoomEnabled = YES;
mapView.scrollEnabled = YES;
mapView.showsUserLocation = YES;
MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
region.span.longitudeDelta = 0.005;
region.span.latitudeDelta = 0.005;
[mapView setRegion:region animated:YES];
[mapView setDelegate:self];
// Download JSON Feed
NSDictionary *feed = [self downloadFeed];
NSArray *streams = (NSArray *)[feed valueForKey:#"stream"];
int Info;
for (Info = 0; Info < streams.count; Info++) {
NSDictionary *stream = (NSDictionary *)[streams objectAtIndex:Info];
NSLog(#"Time: %#", [stream valueForKey:#"Time"]);
NSLog(#"Type: %#", [stream valueForKey:#"Type"]);
NSLog(#"Longitude: %#", [stream valueForKey:#"Longitude"]);
NSLog(#"Latitude: %#", [stream valueForKey:#"Latitude"]);
double lat = [[stream valueForKey:#"Latitude"] doubleValue];
double lon = [[stream valueForKey:#"Longitude"] doubleValue];
NSString *ttype = [[NSString alloc] initWithFormat: #"%#", [stream valueForKey:#"Type"]];
selectedType = ttype;
CLLocationCoordinate2D coord = {lat, lon};
DisplayMap *ann = [[DisplayMap alloc] init];
ann.title = [NSString stringWithFormat: #"%#", [stream valueForKey:#"Type"]];
ann.subtitle = [NSString stringWithFormat: #"%#", [stream valueForKey:#"Time"]];
ann.coordinate = coord;
[mapView addAnnotation:ann];
}
}
}
}
-(void)viewWillAppear { }
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
CLLocationCoordinate2D loc = [newLocation coordinate];
[mapView setCenterCoordinate:loc];
}
-(IBAction)refreshMap:(id)sender {
// Download JSON Feed
NSDictionary *feed = [self downloadFeed];
NSArray *streams = (NSArray *)[feed valueForKey:#"stream"];
int Info;
for (Info = 0; Info < streams.count; Info++) {
NSDictionary *stream = (NSDictionary *)[streams objectAtIndex:Info];
NSLog(#"Time: %#", [stream valueForKey:#"Time"]);
NSLog(#"Type: %#", [stream valueForKey:#"Type"]);
NSLog(#"Longitude: %#", [stream valueForKey:#"Longitude"]);
NSLog(#"Latitude: %#", [stream valueForKey:#"Latitude"]);
double lat = [[stream valueForKey:#"Latitude"] doubleValue];
double lon = [[stream valueForKey:#"Longitude"] doubleValue];
NSString *ttype = [[NSString alloc] initWithFormat: #"%#", [stream valueForKey:#"Type"]];
selectedType = ttype;
CLLocationCoordinate2D coord = {lat, lon};
DisplayMap *ann = [[DisplayMap alloc] init];
ann.title = [NSString stringWithFormat: #"%#", [stream valueForKey:#"Type"]];
ann.subtitle = [NSString stringWithFormat: #"%#", [stream valueForKey:#"Time"]];
ann.coordinate = coord;
[mapView addAnnotation:ann];
}
}
-(MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation {
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil; //return nil to use default blue dot view
static NSString *AnnotationViewID = #"annotationViewID";
MKAnnotationView *annotationView = (MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
if (annotationView == nil) {
annotationView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID] autorelease];
}
annotationView.canShowCallout = YES;
if ([annotationView.annotation.title isEqualToString:#"Selected"]) {
UIImage *pinImage = [UIImage imageNamed:#"icon_selected.png"];
[annotationView setImage:pinImage];
}
annotationView.annotation = annotation;
return annotationView;
}
- (void)dealloc {
[mapView release];
self.adView.delegate = nil;
self.adView = nil;
[super dealloc];
}
#end
From UIViewController.h:
- (void)viewWillAppear:(BOOL)animated;
viewWillAppear is not the same as viewWillAppear:. Perhaps if you override the proper method it might work?
I think more details are needed. If viewWillAppear is not getting called then it is probably something to do with the way you are setting up the views.
These two links should give you some pointers.
How do I have a view controller run updating code when it is brought to the top of the stack of views?
and
What's the proper way to add a view controller to the view hierarchy?

How to draw a route between two locations in a MapView in iPhone?

The below code is implemented it shows current location with blue color blinking and destination location with pin.
Now I need to draw route from my current location to destination location.
I don't know how to configure my current location to destination location to draw route in this code.
//NSString *latlong = [[NSString stringWithFormat:#"%f, %f", currentLocation.latitude, currentLocation.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//NSString *dlatlong = [[NSString stringWithFormat:#"%f, %f", coordinate.latitude, coordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//NSString *url = [NSString stringWithFormat: #"http://maps.google.com/maps?ll=%#&saddr=%#&daddr=%#",
//latlong, latlong, dlatlong];
//[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
#import "MapViewController.h"
#implementation AddressAnnotation
#synthesize coordinate;
//#synthesize currentLocation;
- (NSString *)subtitle{
//return #"Sub Title";
return [NSString stringWithFormat:#"%lf, %lf", coordinate.latitude, coordinate.longitude];
}
- (NSString *)title{
//return #"Title";
return #"Allure-Exclusive";
//return [NSString stringWithFormat:#"%lf, %lf", coordinate.latitude, coordinate.longitude];
}
-(id)initWithCoordinate:(CLLocationCoordinate2D) c{
coordinate=c;
NSLog(#"%f,%f",c.latitude,c.longitude);
return self;
}
#end
#implementation MapViewController
#synthesize address;
#synthesize currentLocation;
static MapViewController *sharedInstance;
+(MapViewController *)sharedInstance{
#synchronized (self)
{
if (!sharedInstance)
[[MapViewController alloc]init];
}
return sharedInstance;
}
+(id)alloc{
#synchronized(self){
NSAssert(sharedInstance==nil,"Attempted to allocate a second instance of a singleton LocationController.");
sharedInstance = [super alloc];
}
return sharedInstance;
}
-(id)init{
if(self==[super init]){
self.currentLocation=[[CLLocation alloc]init];
locationManager=[[CLLocationManager alloc]init];
locationManager.delegate=self;
[self start];
}
return self;
}
-(void)start{
NSLog(#"Start");
mapView.showsUserLocation=YES;
[locationManager startUpdatingLocation];
}
-(void)stop{
mapView.showsUserLocation=NO;
[locationManager stopUpdatingLocation];
}
-(BOOL)locationKnown{
if (round(currentLocation.speed)==-1)
return NO;
else return YES;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
if (abs([newLocation.timestamp timeIntervalSinceDate:[NSDate date]])<120){
self.currentLocation=newLocation;
}
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
UIAlertView *alert;
alert=[[UIAlertView alloc]initWithTitle:#"Error" message:[error description] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
- (void)locationUpdate:(CLLocation *)location{
[mapView setCenterCoordinate:location.coordinate];
if ([mapView showsUserLocation]==NO)
{[mapView setShowsUserLocation:YES];
}
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
// [self addressLocation];
[super viewDidLoad];
self.title=#"Map-View";
mapView.showsUserLocation=YES;
[self showAddress];
NSLog(#"address is %#",address);
//NSString *latlong = [[NSString stringWithFormat:#"%f, %f", currentLocation.latitude, currentLocation.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//NSString *dlatlong = [[NSString stringWithFormat:#"%f, %f", coordinate.latitude, coordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//NSString *url = [NSString stringWithFormat: #"http://maps.google.com/maps?ll=%#&saddr=%#&daddr=%#",
//latlong, latlong, dlatlong];
//[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}
-(void)showAddress{
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta=0.5f;
span.longitudeDelta=0.5f;
CLLocationCoordinate2D location = [self addressLocation];
region.span=span;
region.center=location;
if(addAnnotation != nil) {
[mapView removeAnnotation:addAnnotation];
[addAnnotation release];
addAnnotation = nil;
}
addAnnotation = [[AddressAnnotation alloc] initWithCoordinate:location];
[mapView addAnnotation:addAnnotation];
[mapView setRegion:region animated:TRUE];
[mapView regionThatFits:region];
}
-(CLLocationCoordinate2D) addressLocation {
NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv",
[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
// NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
NSString *locationString=[NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSUTF8StringEncoding error:nil];
NSLog(#"locationString %#",locationString);
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];
NSLog(#"listItems %#",[listItems objectAtIndex:2]);
}
else {
//Show error
}
CLLocationCoordinate2D location;
location.latitude = latitude;
location.longitude = longitude;
return location;
}
- (MKAnnotationView *) mapView:(MKMapView *)mapView1 viewForAnnotation:(id <MKAnnotation>) annotation{
if (annotation==mapView.userLocation)
{
mapView1.userLocation.title=#"Current Location";
[mapView1 setRegion:MKCoordinateRegionMakeWithDistance(mapView.userLocation.coordinate, 1000, 1000)animated:YES];
return nil;
}
else {
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"currentloc"];
annView.pinColor = MKPinAnnotationColorRed;
annView.animatesDrop=YES;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5,5);
return annView;
}
}
//NSString *latlong = [[NSString stringWithFormat:#"%f, %f", currentLocation.latitude, currentLocation.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//NSString *dlatlong = [[NSString stringWithFormat:#"%f, %f", coordinate.latitude, coordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//NSString *url = [NSString stringWithFormat: #"http://maps.google.com/maps?ll=%#&saddr=%#&daddr=%#",
// latlong, latlong, dlatlong];
//[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Overriden to allow any orientation.
return YES;
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// [self stop];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[address release];
[currentLocation release];
[locationManager release];
[super dealloc];
}
#end
There is no feature to draw directions from source to destination in the map view using MKMapKit frame work.
You have to show directions using Google Maps in the iPhone by using the following code.
NSURL *url =[NSURL URLWithString:[NSString stringWithFormat:#"http://maps.google.com/maps?f=d&source=s_d&saddr=%#&daddr=%#&hl=en",[currentLoc stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] ,[destLocation stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
[[UIApplication sharedApplication] openURL:url];
If you wrote this code when the directions button clicked. Then the App will close and Google Maps will open and it will shows the direction.
NSString *latlong = [[NSString stringWithFormat:#"%f, %f", mapView.userLocation.location.coordinate.latitude, mapView.userLocation.location.coordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *dlatlong = [[NSString stringWithFormat:#"%f, %f",52.366428f,4.896349f] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *url = [NSString stringWithFormat: #"http://maps.google.com/maps?ll=%#&saddr=%#&daddr=%#",
latlong, latlong, dlatlong];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
I went with this code... it shows the destination perfect and userlocation is at 0.000000,0.000000 values.
I need to see current location too.

CLLocationDistance: Cant get "getDistanceFrom" to work

view based app,
.m
- (void)viewDidLoad {
[super viewDidLoad];
self.locationManager = [[[CLLocationManager alloc] init] autorelease];
self.locationManager.delegate = self;
[[self locationManager] startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
CurrentLocation = newLocation;
[locationManager stopUpdatingLocation];
myActivity.hidden=YES;
[self reStart];
}
-(void)reStart{
[self checkAndCreateDatabase]; //Sucess
[self readFromDatabase]; //Success if I comment the get distance part
[self sort]; //Success
}
-(void) readFromDatabase {
...
CLLocationCoordinate2D cord;
cord.latitude = [[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)] doubleValue];
cord.longitude =[[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)] doubleValue];
NSDate *today = [NSDate date];
CLLocation *objectLocation = [[CLLocation alloc] initWithCoordinate:cord altitude:1 horizontalAccuracy:1 verticalAccuracy:-1 timestamp:today];
CLLocationDistance distance = [objectLocation getDistanceFrom:CurrentLocation]/1000;
NSLog([NSString stringWithFormat:#"%.0f", distance]);
}
What is wrong?
debugger says:
obj_msgSend
0x912e8688 <+0024> mov 0x20(%edx),%edi
object from database:
long: 59.291114
lat: 17.816191
Use distanceFromLocation: instead
Is CurrentLocation an instance-variable/property? You are setting it directly without an accessor and you are not retaining it. If it is released before you use it in getDistance: it will cause a crash.
If it is a property use the self.CurrentLocation to ensure it is retained.
Also, the construction...
NSLog([NSString stringWithFormat:#"%.0f", distance]);
... is risky and redundant. Use...
NSLog(#"%.0f", distance);
... instead.