Placemark not giving city name in iOS 6 - iphone

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]

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

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

I want to get the Location name from the Coordinate value in MapKit for iPhone

I want to get the location name from the coordinate value. Here is code,
- (void)viewWillAppear:(BOOL)animated {
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = 39.281516;
zoomLocation.longitude= -76.580806;
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 0.5*METERS_PER_MILE, 0.5*METERS_PER_MILE);
MKCoordinateRegion adjustedRegion = [_mapView regionThatFits:viewRegion];
[_mapView setRegion:adjustedRegion animated:YES];
}
So, From that Latitude and longitude , i want to know that location name.
The Below code shall work in ios5 and above
CLGeocoder *ceo = [[CLGeocoder alloc]init];
CLLocation *loc = [[CLLocation alloc]initWithLatitude:32.00 longitude:21.322]; //insert your coordinates
[ceo reverseGeocodeLocation:loc
completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
if (placemark) {
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);
}
else {
NSLog(#"Could not locate");
}
}
];
-(NSString *)getAddressFromLatLon:(double)pdblLatitude withLongitude:(double)pdblLongitude
{
NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%f,%f&output=csv",pdblLatitude, pdblLongitude];
NSError* error;
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
// NSLog(#"%#",locationString);
locationString = [locationString stringByReplacingOccurrencesOfString:#"\"" withString:#""];
return [locationString substringFromIndex:6];
}
Use this method
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation: zoomLocation completionHandler:^(NSArray* placemarks, NSError* error){
}
];
In iOS 5.0 and later, you can use CLGeocoder of Core Location framework, as for iOS lower than 5.0, MKReverseGeocoder of Map Kit Framework. Good luck!
Here is block to get address string from current location
in .h file
typedef void(^addressCompletionBlock)(NSString *);
-(void)getAddressFromLocation:(CLLocation *)location complationBlock:(addressCompletionBlock)completionBlock;
in .m file
#pragma mark - Get Address
-(void)getAddressFromLocation:(CLLocation *)location complationBlock:(addressCompletionBlock)completionBlock
{
//Example URL
//NSString *urlString = #"http://maps.googleapis.com/maps/api/geocode/json?latlng=23.033915,72.524267&sensor=true_or_false";
NSString *urlString = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=true_or_false",location.coordinate.latitude, location.coordinate.longitude];
NSError* error;
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:[locationString dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:NULL];
NSString *strFormatedAddress = [[[jsonObject valueForKey:#"results"] objectAtIndex:0] valueForKey:#"formatted_address"];
completionBlock(strFormatedAddress);
}
and to call function
CLLocation* currentLocation = [[CLLocation alloc] initWithLatitude:[SharedObj.current_Lat floatValue] longitude:[SharedObj.current_Long floatValue]];
[self getAddressFromLocation:currentLocation complationBlock:^(NSString * address) {
if(address) {
NSLog(#"Address:: %#",address);
}
}];

Not getting Address from latitude and longitude

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).

Writing to a plist in a LocationManager method

I am trying to write a latitude value and longitude value to a plist inside a LocationManager method.
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
NSString *latitude = [[NSString alloc] initWithFormat:#"%g", newLocation.coordinate.latitude];
NSString *longitude = [[NSString alloc] initWithFormat:#"%g", newLocation.coordinate.longitude];
NSString *filePath = [[NSBundle mainBundle] pathForResource:
#"PlayerData" ofType:#"plist"];
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
[plistDict setValue:latitude forKey:#"MyLatitude"];
[plistDict setValue:longitude forKey:#"MyLongitude"];
[plistDict writeToFile:filePath atomically: YES];
myLatitude.text = latitude;
myLongitude.text = longitude;
NSLog(#"Location: %#", [newLocation description]);
}
For some reason it never writes the value to the plist, but prints out the values correctly.
NSLog(#"Lat i s:%# Lon is :%#", latitude, longitude);
What would cause this not to update/write to the plist?
Thanks
iOS applications are sandboxed, so you can't write to the application bundle. You need to write to one of these directories. Which one you need to write to depends on what kind of data it is.
You can't write to the main bundle (may work in simulator but not device).
Try saving the file to the Documents folder instead.