Not getting a correct address from Latitude & Longitude - ios

I want to get the true postal address from the Latitude & Longitude, however is not working well. Maybe I am note using the right APIs or etc.
For example I have the following code
var location = CLLocation(latitude:currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude)
CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
print(location)
if error != nil {
print("Reverse geocoder failed with error" + error!.localizedDescription)
return
}
if placemarks!.count > 0 {
let pm = placemarks![0] as! CLPlacemark
street = String(pm.thoroughfare!)
city = String(pm.locality!)
state = String(pm.administrativeArea!)
print(pm.locality)
print(pm.administrativeArea)
print(pm.thoroughfare)
self.utility.setMyLocation(dName, longitude: long, latitude: lat, street: street, city: city, state: state)
locManager.stopUpdatingLocation()
}
else {
print("Problem with the data received from geocoder")
}
})
However I am not getting the true address. For example let say if that long and lat address is
123 East Street
I get something like only East Street (with no number) or near by road.
What do I need to do inorder to get the real address?

Im not sure if this is what your looking for but its what i currently use to get a nice readable address. I also send these values to my Application delegate for referencing later if i need them. I don't have it written in Swift however just in Objective C. :/ But i think the key is reverseGeocodeLocation
#pragma mark - location Manager update and FUNCTIONS
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
NSLog(#"%s Failed with Error: %#", __PRETTY_FUNCTION__, error);
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(#"%s Update to Location: %#", __PRETTY_FUNCTION__, newLocation);
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
NSString *longitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
NSString *latitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
NSLog(#"Longitude: %#", longitude);
NSLog(#"Latitude: %#", latitude);
// Set current values to the AppDelegate for refrencing
appDelegate.locationDetailLon = longitude;
appDelegate.locationDetailLat = latitude;
}
// Stop Location Manager to save power
[locationManager stopUpdatingLocation];
// Reverse Geocoding
NSLog(#"Translating and getting the Address");
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
// NSLog(#"Found placemarks: %#, error: %#", placemarks, error);
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
NSString *address = [NSString stringWithFormat:#"%# %#\n%# %#\n%#\n%#",
placemark.subThoroughfare, placemark.thoroughfare,
placemark.postalCode, placemark.locality,
placemark.administrativeArea,
placemark.country];
NSLog(#"Address:\n%#", address);
// Set current values to the AppDelegate for refrencing
appDelegate.locationDetailState = placemark.administrativeArea;
appDelegate.locationDetailCountry = placemark.country;
appDelegate.locationDetailCity = placemark.locality;
appDelegate.locationDetailPostCode = placemark.postalCode;
} else {
NSLog(#"%s ERROR: %#", __PRETTY_FUNCTION__, error.debugDescription);
}
} ];
}

Related

Why use CLGeocoder with an array of "placemarks"?

When trying to use CLGeocoder, I got this example from an online tutorial:
https://www.appcoda.com/how-to-get-current-location-iphone-user/
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
longitudeLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
latitudeLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
// Reverse Geocoding
NSLog(#"Resolving the Address");
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(#"Found placemarks: %#, error: %#", placemarks, error);
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
addressLabel.text = [NSString stringWithFormat:#"%# %#\n%# %#\n%#\n%#",
placemark.subThoroughfare, placemark.thoroughfare,
placemark.postalCode, placemark.locality,
placemark.administrativeArea,
placemark.country];
} else {
NSLog(#"%#", error.debugDescription);
}
} ];
}
However, I don't quite understand why it takes an array of "placemarks" in the completion handler part and why we should use the last object of "placemarks" (I also see people using the first object?).
I've read through the apple document but didn't find any good explanation in terms of use:
https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLGeocoder_class/
You are reverse-geocoding a lat/long. It might yield more than one address. If you get more than one and don't care which one you use, it's just as valid to extract the first or last placemark object in the array.
(You'll probably only get one match most of the time, in which case the first and last element are the same thing.)

Objective-C: Finding User Location (Not on a Map)

I am trying to make my app find a user's location in an address-like form (located after the "Reverse Geocoding" comment). Below is my code:
- (IBAction)getuserlocation:(id) sender{
//Getting Location
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
NSLog(address);
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error" message:#"Failed to Get Your Location" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
longitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
latitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
// Stop Location Manager
[locationManager stopUpdatingLocation];
// Reverse Geocoding
NSLog(#"Resolving the Address");
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(#"Found placemarks: %#, error: %#", placemarks, error);
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
address = [NSString stringWithFormat:#"%# %#\n%# %#\n%#\n%#",
placemark.subThoroughfare, placemark.thoroughfare,
placemark.postalCode, placemark.locality,
placemark.administrativeArea,
placemark.country];
} else {
NSLog(#"%#", error.debugDescription);
}
} ];
}
My issue is that the compiler only prints out "(null)". (The line where I do this is located in the "getuserlocation" IBAction.) I'm not sure why this is. I've tested the app on an actual iPhone 6 Plus, which unlike the simulator, has access to location services.
If anyone would be able to point out where the error/problem in my code is, causing it to print out null, I would greatly appreciate it. Thanks in advance to all who reply.
***BTW: The following lines are in my viewDidLoad section:
locationManager = [[CLLocationManager alloc] init];
geocoder = [[CLGeocoder alloc] init];
You are logging address long before you get a location and convert it to an address.
Move the NSLog(address); to just after where you actually assign a value to address.
BTW - it should be more like: NSLog(#"Address: %#, address);.

location updating in simulator but not in device

I am trying to get the user's updated location by using core location framework.It is working in simulator, but not in ipad/iphone.I am using the following code to get it. In simulator, i am using freeway drive.
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:
(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
CLLocation *currentLocation=newLocation;
NSLog(#"location : %#",currentLocation);
if(currentLocation !=nil)
{
self.latitudelabel.text = [NSString
stringWithFormat:#"%.8f",currentLocation.coordinate.latitude];
self.longitudelabel.text = [NSString
stringWithFormat:#"%.8f",currentLocation.coordinate.longitude];
}
CLLocationDistance distance = [newLocation distanceFromLocation:oldLocation];
NSLog(#"Calc.distance%f",distance);
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^
(NSArray *placemarks, NSError *error)
{
if(error == nil && [placemarks count]>0)
{
placemark = [placemarks lastObject];
NSLog(#"Country %#",placemark.country);
NSLog(#"Area %#",placemark.administrativeArea);
NSLog(#"City %#",placemark.locality);
NSLog(#"Code %#",placemark.postalCode);
NSLog(#"Road %#",placemark.thoroughfare);
NSLog(#"Number %#",placemark.subThoroughfare);
self.addresslabel.text = [NSString stringWithFormat:#"%# %#
\n %# %# \n %# \n %#",
placemark.subThoroughfare, placemark.thoroughfare,
placemark.postalCode, placemark.locality,
placemark.administrativeArea,
placemark.country];
}
else
{
NSLog(#"tktk%#",error.debugDescription);
}
}];
}
Go in settings > Privacy > Location services > Your app > Always.
You can also check other alternatives posted in the following question Core Location not working in iOS 8

Location Service doesn't provide all data in iOS SDK

It shows me (null) (null),Ahmedabad Gujarat (null) (null) when following code executes.
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
_CurrentLocation = newLocation.coordinate;
CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error)
{
for (CLPlacemark * placemark in placemarks)
{
NSString *addressTxt = [NSString stringWithFormat:#"%# %#,%# %# %# %#",
[placemark subThoroughfare],[placemark thoroughfare],
[placemark locality], [placemark administrativeArea], [placemark subLocality],[placemark subAdministrativeArea]];
NSLog(#" >> %#",addressTxt);
self.strLocation = [placemark locality];
}
}];
}
How to get other values ? Is location service will not provide these data in my area ?
And if not then any alternative to get this data ?

locationManager is not updating the Location

i am using this code to get the Location ,using simulator , but its not giving me any output .
also if someone suggest me a solution of this or a better alternative solution.\
-(void)viewDidAppear:(BOOL)animated
{
_locationManager.delegate=self;
[_locationManager startUpdatingLocation];
[self.geoCoder reverseGeocodeLocation: _locationManager.location completionHandler:
^(NSArray *placemarks, NSError *error) {
if (error) {
return;
}
if (placemarks && placemarks.count > 0)
{
CLPlacemark *placemark = placemarks[0];
NSDictionary *addressDictionary =
placemark.addressDictionary;
NSString *address = [addressDictionary
objectForKey:(NSString *)kABPersonAddressStreetKey];
NSString *city = [addressDictionary
objectForKey:(NSString *)kABPersonAddressCityKey];
NSString *state = [addressDictionary
objectForKey:(NSString *)kABPersonAddressStateKey];
NSString *zip = [addressDictionary
objectForKey:(NSString *)kABPersonAddressZIPKey];
NSString *Countrynsme = [addressDictionary
objectForKey:(NSString *)kABPersonAddressCountryKey];
_requestorAddressText.Text = address;
_requestorCityText.text = city;
_requestorPostalText.text = zip;
_CountryrequestorText.text = Countrynsme;
_requestorStateText.text = state;
}
}];
[_locationManager stopUpdatingLocation];
}
CLLocationManager is an asynchronous API. You need to wait for the result of CLLocationManager before you geocode the location.
Start listening for location manager updates using the CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSTimeInterval interval = [newLocation.timestamp timeIntervalSinceNow];
if (interval < 0) {
interval = -interval;
}
// Reject stale location updates.
if (interval < 30.0) {
// Start geocoding
[geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
// Use geocoded results
...
}];
}
// If you're done with getting updates then do [manager stopUpdatingLocation]
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
// Handle error. Perhaps [manager stopUpdatingLocation]
}
Then viewDidAppear just bootstrap's the location lookup:
- (void)viewDidAppear {
// PS: You're missing a call to [super viewDidAppear]
[super viewDidAppear];
// Start lookup for location
_locationManager.delegate=self;
[_locationManager startUpdatingLocation];
}
PS: In dealloc don't forget to stop updating location, cancel geocode and nil the delegates for locationManager.

Resources