How to get device location name in iPhone? - 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

Related

how to move in map of iphone simulator ? dynamic Latitude & Longitude getting but not locate in iphone simulator?

-(CLLocationCoordinate2D)getGeoCoding:(NSString *)address
{
NSString *req = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%#",address];
NSURL *url = [NSURL URLWithString:req];
NSError *error;
//NSURLResponse *response;
CLLocationCoordinate2D findlocation;
NSData *data = [[NSData alloc]initWithContentsOfURL:url];
NSMutableDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:Nil error:&error];
if(error)
{
NSLog(#"%#",[error localizedDescription]);
findlocation.latitude=0.0;
findlocation.longitude =0.0;
}
else
{
NSArray *results = (NSArray *)responseDictionary[#"results"];
NSDictionary *firstitem = (NSDictionary *)[results objectAtIndex:0];
NSLog(#"%#",firstitem);
NSDictionary *geometry = (NSDictionary *)[firstitem valueForKey:#"geometry"];
NSLog(#"%#",geometry);
NSDictionary *location = (NSDictionary *)[geometry valueForKey:#"location"];
NSLog(#"%#",location);
NSNumber *lat = (NSNumber *)[location valueForKey:#"lat"];
NSLog(#"%#",lat);
NSNumber *lng = (NSNumber *)[location valueForKey:#"lng"];
NSLog(#"%#",lng);
findlocation.latitude = [lat doubleValue];
findlocation.longitude = [lng doubleValue];
}
return findlocation;
}
i getting location from above code.
-(void)getLocation:(id)sender
{
NSString *str = self.textView.text;
CLLocationCoordinate2D location;
location=[self getGeoCoding:str];
self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.delegate=self;
self.mapView.showsUserLocation =YES;
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(location, 0.3*METERS_PER_MILES, 0.3*METERS_PER_MILES);
[self.locationManager startUpdatingLocation];
[self.mapView reloadInputViews];
[self.mapView setRegion:viewRegion animated:YES];
}
location code is getting after the above function.
function is called but that do not work in iPhone simulator..?
if the set any setting Please tell me what the problem in code because iPhone simulator map not move from current location..
Is it Possible? How?

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 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]

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