how to get geolocation city name in iphone? - 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);
}];

Related

Load Map View on MKMapView

I want to load map on MKMapView.
Basically what i want to do is,
I want to load Particular Venue in my MapView.
My Database contains lot of Venues, according to requirement, i am fetching Venue and i want to load that Venue in my mapView.
for eg: I got this as Venue: #"100 Oxford Street, London, W1D 1LL, 020 7636 0933" from Database, then i want to load this location in my mapView
Thanks in advance.
EDIT:
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
NSString *venue= #"100 Oxford Street, London, W1D 1LL, 020 7636 0933";
[geocoder geocodeAddressString:venue completionHandler:^(NSArray *placemarks, NSError *error)
{
if ([placemarks count] > 0)
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
CLLocation *loc = placemark.location;
CLLocationCoordinate2D _venue = loc.coordinate;
NSLog(#"_venue:=%f",loc.coordinate);
MKPointAnnotation *venueAnnotation = [[MKPointAnnotation alloc]init];
[venueAnnotation setCoordinate:_venue];
[venueAnnotation setTitle:#"Venue"];
[MapVw addAnnotation:venueAnnotation];
}
}
];
- (IBAction)BtnClick:(id)sender {
NSLog(#"Map ");
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:#"100 Oxford Street, London, W1D 1LL, 020 7636 0933"
completionHandler:^(NSArray* placemarks, NSError* error)
{
if (placemarks && placemarks.count > 0)
{
CLPlacemark *topResult = [placemarks objectAtIndex:0];
MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];
[self.MapView addAnnotation:placemark];
CLLocationCoordinate2D _venue = placemark.coordinate;
[self.MapView setCenterCoordinate:_venue];
MKCoordinateRegion region = self.MapView.region;
region.span.longitudeDelta = 1.0;
region.span.latitudeDelta = 1.0;
[self.MapView setRegion:region animated:YES];
}
}
];
}
Steps:
1. Import CoreLocation.framework and MapKit.framework.
2. Use CoreLocation class Geocoder's method :
geoCodeAddressString:completionHandler:
NSString *venue= #"100 Oxford Street, London, W1D 1LL, 020 7636 0933";
[_geoCoder geocodeAddressString:venue completionHandler:^(NSArray *placemarks, NSError *error)
{
if ([placemarks count] > 0)
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
CLLocation *loc = placemark.location;
CLLocationCoordinate2D _venue = loc.coordinate;
}
});
]
[self performSelector:#selector(createVenueAnnotation) withObject:nil afterDelay:5];
UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc]init];
[_mapView addSubview:activity];
[activity startAnimating];
Step 3. If you want to place a MKPointAnnotation on the venue point.
- (void)createVenueAnnotation{
[activity stopAnimating];
[activity removeFromSuperview];
MKPointAnnotation *venueAnnotation = [[MKPointAnnotation alloc]init];
[venueAnnotation setCoordinate:_venue];
[venueAnnotation setTitle:#"Venue"];
[_mapView addAnnotation:venueAnnotation];
}
Step 4: Center your map around the venue.
// you need to call this function
- (void)centerMapAroundVenue
{
MKMapRect rect = MKMapRectNull;
MKMapPoint venuePoint = MKMapPointForCoordinate(_venue);
rect = MKMapRectUnion(rect, MKMapRectMake(venuePoint .x, venuePoint .y, 0, 0));
MKCoordinateRegion region = MKCoordinateRegionForMapRect(rect);
[_mapView setRegion:region animated:YES];
}
Here is simple scenario :
Get the Co-ordinates of the Address using GeoCoder
Using the Co-ordinatation ,Add the Annotation to the MapView.
Do something Like this to get the CLlocationCoordinate :
- (CLLocationCoordinate2D) geoCodeUsingAddress:(NSString *)address
{
double latitude = 0, longitude = 0;
NSString *esc_addr = [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *req = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%#", esc_addr];
NSString *result = [NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:NULL];
if (result) {
NSScanner *scanner = [NSScanner scannerWithString:result];
if ([scanner scanUpToString:#"\"lat\" :" intoString:nil] && [scanner scanString:#"\"lat\" :" intoString:nil]) {
[scanner scanDouble:&latitude];
if ([scanner scanUpToString:#"\"lng\" :" intoString:nil] && [scanner scanString:#"\"lng\" :" intoString:nil]) {
[scanner scanDouble:&longitude];
}
}
}
CLLocationCoordinate2D center;
center.latitude = latitude;
center.longitude = longitude;
return center;
}
Using the Center just add the annotation to the MapView.
[self.mapView addAnnotation:<annotationName>];
Plz go through this link For more info.
Hope this helps.

Placemark not giving zip code to find out weather information

I want to find out the weather from the current location.
For that I used the code as
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
[self.locationManager stopUpdatingLocation];
self.location = newLocation;
// NSLog(#"lat long = %f,%f",self.location.coordinate.latitude,self.location.coordinate.longitude);
// Geocode coordinate (normally we'd use location.coordinate here instead of coord).
// This will get us something we can query Google's Weather API with
if (boolCurrentlyWorking == NO) {
CLGeocoder* reverseGeocoder = [[CLGeocoder alloc] init];
if(reverseGeocoder)
{
[reverseGeocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark* placemark = [placemarks objectAtIndex:0];
if (placemark) {
//Using blocks, get zip code
NSString *zipCode = [placemark.addressDictionary objectForKey:(NSString*)kABPersonAddressZIPKey];
NSLog(#"placemark : %# zipcode : %#",placemark.addressDictionary,zipCode);
}
}];
}else{
MKReverseGeocoder *geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:self.location.coordinate];
geocoder.delegate = self;
[geocoder start];
}
}
boolCurrentlyWorking = YES;
}
I am not getting zip code here.
Also found out that this method of didupdate location has been deprecated and new method is
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *location = [locations lastObject];
CLLocation *newlocation = location;
NSLog(#"location : %#",location);
CLGeocoder* reverseGeocoder = [[CLGeocoder alloc] init];
if(reverseGeocoder)
{
[reverseGeocoder reverseGeocodeLocation:newlocation completionHandler:^(NSArray *placemarks, NSError *error) {
for(CLPlacemark *placemark in placemarks)
{
NSLog(#"plcaemark desc : %#",[placemark description]);
}
}];
}
}
But it also does not contain zipcode.
I got this description
{
   Country = India;
   CountryCode = IN;
   FormattedAddressLines =     (
       NH8C,
       Gujarat,
       India
   );
   Name = NH8C;
   State = Gujarat;
   Street = NH8C;
   Thoroughfare = NH8C;
}
Is there like it does not provide zipcode information and we have to build it? If yes then how?
First of all We are not getting any zip code or postal code for India.
Also Google API has been stop working.
I used yahoo api to find out weather.
Here is the code that might help someone
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
[self.locationManager stopUpdatingLocation];
self.location = newLocation;
NSString *linkForWoeid = [NSString stringWithFormat:#" http://where.yahooapis.com/geocode?location=%f,%f&flags=J&gflags=R&appid=zHgnBS4m",self.location.coordinate.latitude,self.location.coordinate.longitude];
NSURL *woeidURL = [NSURL URLWithString:linkForWoeid];
NSData *WoeidData = [NSData dataWithContentsOfURL:woeidURL];
if (WoeidData != NULL)
{
NSError *woeiderr = nil;
NSDictionary *aDicWOEIDResp = [NSJSONSerialization JSONObjectWithData:WoeidData options:NSJSONReadingMutableContainers error:&woeiderr];
NSDictionary *aDictWOEID = [[[[aDicWOEIDResp objectForKey:#"ResultSet"]objectForKey:#"Results"]objectAtIndex:0]objectForKey:#"woeid"];
NSString *address=[NSString stringWithFormat:#"http://weather.yahooapis.com/forecastrss?w=%#",aDictWOEID];
ICB_WeatherConditions *icbWeather = [[ICB_WeatherConditions alloc] initWithQuery:address];
}
#import "ICB_WeatherConditions.m"
- (ICB_WeatherConditions *)initWithQuery:(NSString *)query
{
if (self = [super init])
{
NSURL *url = [NSURL URLWithString:query];
CXMLDocument *parser = [[[CXMLDocument alloc] initWithContentsOfURL:url options:0 error:nil] autorelease];
NSDictionary *namespaceMedia = [NSDictionary dictionaryWithObject:#"http://xml.weather.yahoo.com/ns/rss/1.0" forKey:#"yweather"];
NSArray *nodes = [parser nodesForXPath:#"//channel" error:nil];
for (CXMLNode *node in nodes) {
if ([node kind] == CXMLElementKind)
{
CXMLElement *element = (CXMLElement *)node;
for(int i=0;i<[element childCount];i++)
{
NSString *strKey = [[element childAtIndex:i] name];
if([strKey isEqual:#"location"])
{
location = [self stringForXPath:#"#city" ofNode:[element childAtIndex:i] withNameSpace:namespaceMedia];
}
else if([strKey isEqual:#"item"])
{
NSArray *nodeItem = [element nodesForXPath:#"//item" error:nil];
CXMLElement *elementItem = [nodeItem objectAtIndex:0];
for(int j=0;j<[elementItem childCount];j++){
NSString *strKeyItem = [[elementItem childAtIndex:j] name];
if([strKeyItem isEqual:#"condition"]){
condition =[self stringForXPath:#"#text" ofNode:[elementItem childAtIndex:j] withNameSpace:namespaceMedia];
currentTemp = [[self stringForXPath:#"#temp" ofNode:[elementItem childAtIndex:j] withNameSpace:namespaceMedia] intValue];
}
else if([strKeyItem isEqual:#"forecast"])
{
NSString *date = [self stringForXPath:#"#date" ofNode:[elementItem childAtIndex:j] withNameSpace:namespaceMedia];
NSDate *curDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"dd MMM yyyy";
NSString *strCurDate = [dateFormatter stringFromDate:curDate];
if([date isEqual:strCurDate])
{
highTemp = [[self stringForXPath:#"#high" ofNode:[elementItem childAtIndex:j] withNameSpace:namespaceMedia] intValue];
lowTemp = [[self stringForXPath:#"#low" ofNode:[elementItem childAtIndex:j] withNameSpace:namespaceMedia] intValue];
}
}
}
}
else
continue;
}
}
}
}
return self;
}
This is how I get the weather Details.
In my case I only needed Location,Condition,High Temp,Low Temp,Current Temp.

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

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