Not getting Address from latitude and longitude - iphone

I am using following code for get address from current latitude and longitude, But I am not able to get proper response
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
current_latitude=newLocation.coordinate.latitude;
current_longitude=newLocation.coordinate.longitude;
CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
if(placemarks && placemarks.count > 0)
{
CLPlacemark *placemark= [placemarks objectAtIndex:0];
NSString * address = [NSString stringWithFormat:#"%# %#,%# %#", [placemark subThoroughfare],[placemark thoroughfare],[placemark locality], [placemark administrativeArea]];
UIAlertView *art = [[UIAlertView alloc] initWithTitle:address message:nil delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[art show];
[art release];
NSLog(#"%#",address);
}
}];
}

CLLocation has poor coverage at the moment; see this document. It's possible you're trying to geocode a location from a poorly covered area.
If that's the case, there are other geocoders, such as Google's Geocoder (which requires you to display the results on a map).

Related

how to get geolocation city name in iphone?

I have tried this codes for getting the geolocation based values but not able to get the city name. How do I get the city name?
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
double lati = newLocation.coordinate.latitude;
_geo_coder_latitude_lbl.text= [[NSString stringWithFormat:#"%f",lati] retain];
_geocoder_latitude_str=_geo_coder_latitude_lbl.text;
NSLog(#"print lat;%#",_geocoder_latitude_str);
double longi = newLocation.coordinate.longitude;
_geocoder_longitude_lbl.text= [[NSString stringWithFormat:#"%f",longi] retain];
_geocoder_longitude_str=_geocoder_longitude_lbl.text;
NSLog(#"print lat;%#",_geocoder_longitude_str);
[self._geocoder reverseGeocodeLocation: locationManager.location completionHandler:
^(NSArray *placemarks, NSError *error)
{
//Get address
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(#"Placemark array: %#",placemark.addressDictionary );
//String to address
_located_address = [[placemark.addressDictionary valueForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
//Print the location in the console
NSLog(#"Currently address is: %#",_located_address);
// _ex_map_address_lbl.text=_located_address;
}];
[self _storeList_json_parser];
}
See the CLPlacemark docs, [CLPlacemark locatity] will return the city name associated with the placemark.
Check this sample code:
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
double lati = 45.46433;
double longi = 9.18839;
CLLocation *location = [[CLLocation alloc] initWithCoordinate:CLLocationCoordinate2DMake(lati, longi)
altitude:0
horizontalAccuracy:0
verticalAccuracy:0
timestamp:[NSDate date]];
[geocoder reverseGeocodeLocation:location completionHandler:
^(NSArray *placemarks, NSError *error)
{
CLPlacemark *placemark = [placemarks lastObject];
if (error || !placemark)
return;
NSString *city = placemark.locality;
if (!city)
city = placemark.subAdministrativeArea;
NSLog(#"City for location: %#", city);
}];

Placemark not giving city name in iOS 6

I am using this code in which I am getting Placemark but it not giving the city name.
Earlier I am using MKReverse Geocoder to get the placemark in which I am getting the city name but as in iOS 6 it showing deprecated because the Apple developer added everything in CLLocation.
So I used this code:
-(void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
CLLocation *location = [locationManager location];
NSLog(#"location is %#",location);
CLGeocoder *fgeo = [[[CLGeocoder alloc] init] autorelease];
// Reverse Geocode a CLLocation to a CLPlacemark
[fgeo reverseGeocodeLocation:location
completionHandler:^(NSArray *placemarks, NSError *error){
// Make sure the geocoder did not produce an error
// before continuing
if(!error){
// Iterate through all of the placemarks returned
// and output them to the console
for(CLPlacemark *placemark in placemarks){
NSLog(#"%#",[placemark description]);
city1= [placemark.addressDictionary objectForKey:(NSString*) kABPersonAddressCityKey];
NSLog(#"city is %#",city1);
}
}
else{
// Our geocoder had an error, output a message
// to the console
NSLog(#"There was a reverse geocoding error\n%#",
[error localizedDescription]);
}
}
];
}
Here as I am seeing in console in NSLog(#"%#",[placemark description]);
it's giving output like :- abc road name,abc road name, state name,country name.
If you want to NSLog the address you have to compose it doing something like this:
NSString *street = [[placemark addressDictionary] objectForKey:(NSString *)kABPersonAddressStreetKey];
NSString *city = [[placemark addressDictionary] objectForKey:(NSString *)kABPersonAddressCityKey];
NSString *state = [[placemark addressDictionary] objectForKey:(NSString *)kABPersonAddressStateKey];
NSString *country = [[placemark addressDictionary] objectForKey:(NSString *)kABPersonAddressCountryKey];
NSString *zip = [[placemark addressDictionary] objectForKey:(NSString *)kABPersonAddressZIPKey];
NSString *message = [NSString stringWithFormat:#"Address Is: %#, %# %#, %#, %#", street, zip, city, state, country];
NSLog(#"%#", message);
Or you can iterate through the array returned by:
NSArray *array = [[placemark addressDictionary] objectForKey:#"FormattedAddressLines"];
If you want to simply print the dictionary content, do:
NSLog(#"%#", [[placemark addressDictionary] description]);
Three things that I can see could use some attention...
First, this method is deprecated (see documentation here):
(void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
Try using this instead:
(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
Your most current location is the last item in the array locations so:
/*
According to the Apple docs, the array of locations keeps the most recent location as the
last object in the array
*/
CLLocation *location = [locations lastObject];
NSLog(#"%#", location);
Second, if you're using ARC, the autorelease message is unnecessary: CLGeocoder *fgeo = [[CLGeocoder alloc] init]; works fine.
Lastly, according to the Apple documentation for CLPlacemark has a property locality which should return the city for the placemark. So
for(CLPlacemark *placemark in placemarks){
NSLog(#"%#",[placemark description]);
NSString *city1 = [placemark locality];
NSLog(#"city is %#",city1); }
If you just want the city, the addressDictionary property seems to be overkill. According to the documentation here addressDictionary is formatted to return stuff in an ABPerson object, which I'd assume you'd have to parse to get the city. Placemark locality seems much simpler...
I tested my suggestions in a Geocoding app that I'm building and I got the result you're looking for via [placemark locality]

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

CLGeocoder not working

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after app launch
[window addSubview:viewController.view];
[window makeKeyAndVisible];
[window addViewForTouchPriority:viewController.view];
if(self.locationManager==nil){
locationManager=[[CLLocationManager alloc] init];
locationManager.delegate=self;
locationManager.purpose = #"We will try to tell you where you are if you get lost";
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
locationManager.distanceFilter=500;
self.locationManager=locationManager;
}
geoCoder = [[CLGeocoder alloc] init];
if([CLLocationManager locationServicesEnabled]){
[self.locationManager startUpdatingLocation];
}
return YES;
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
lati = [[NSString alloc] initWithFormat:#"%+.6f", newLocation.coordinate.latitude];
NSLog(#"address:%#",lati);
longi = [[NSString alloc] initWithFormat:#"%+.6f", newLocation.coordinate.longitude];
NSLog(#"address:%#",longi);
CLLocationCoordinate2D coord;
coord.latitude = [lati doubleValue];
coord.longitude = [longi doubleValue];
[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);
}];
}
I am using above code to get address by giving latitude and longitude, but control is not entering in to geocoder method, it skips it. Can anybody help me in it.
Thanks in advance.
It doesn't matter, control does not enter in the method, but it works, note the output it will work.
that is normal, because the code inside the reverseGeocodeLocation is execute inside a block.
The execution of the code inside a block occurs in another thread, so is not execute in the main thread, that's why the control don't enter inside the geocoder method.

MKReverseGeocoder returns cities that are not a city?

Hi i am using mkreversegeocoder to find the users current city.It works but when i try it in another location it gives the names of borough/district in my country (Turkey).For example it gives "istanbul" correct but there is no city name like "susurluk" in my country it is a district.Any idea why it returns me districts instead of city name? if you want i would post my code's
edit 1:
-(void)viewDidLoad {
[super viewDidLoad];
manager=[[CLLocationManager alloc]init];
manager.delegate=self;
manager.desiredAccuracy=kCLLocationAccuracyBest;
[manager startUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)aManager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
MKReverseGeocoder *geocoder=[[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate];
geocoder.delegate=self;
[geocoder start];
[manager startUpdatingLocation];
}
-(void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark {
NSDictionary * addressDict= [placemark addressDictionary];
//NSString *country = [addressDict objectForKey:#"Country"];
NSString *city = [addressDict objectForKey:#"City"];
//change the country name into en_US
NSLocale *locale = [NSLocale currentLocale];
NSString *countryCode = [locale objectForKey: NSLocaleCountryCode];
NSLocale *usLocale = [[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"] autorelease];
NSString *country1 = [usLocale displayNameForKey: NSLocaleCountryCode value: countryCode];
[[NSUserDefaults standardUserDefaults] setObject:country1 forKey:#"country"];
[[NSUserDefaults standardUserDefaults] setObject:city forKey:#"city"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
-(void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error {
if (error.code == kCLErrorHeadingFailure) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Problem"
message:#"Can't find the location!"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alertView show];
[alertView release];
[manager stopUpdatingLocation];
}
}
-(void)locationManager:(CLLocationManager *)manager1 didFailWithError:(NSError *)error {
if (error.code != kCLErrorDenied) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Problem"
message:#"Can't find the location!"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alertView show];
[alertView release];
[manager stopUpdatingLocation];
}
}
You can get the correct answer by using the google map api in which you have to send the lat/long of the place and you will get answer in the form of json/xml. Please check out this question
Reverse Geocoding With Google Map API And PHP To Get Nearest Location Using Lat,Long coordinates