I need to get the exact current address (country,state,city) of user. So I have gone to find latitude and longitude and then find out from it by using reverse geocoding.But unable to get latitude and longitude itself.I m using xcode 4.1 and testing in iphone simulator.
This is the code I m working on:
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
[locationManager startUpdatingLocation];
NSLog(#"%#", [self deviceLocation]);
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
int degrees = newLocation.coordinate.latitude;
double decimal = fabs(newLocation.coordinate.latitude - degrees);
int minutes = decimal * 60;
double seconds = decimal * 3600 - minutes * 60;
NSString *lat = [NSString stringWithFormat:#"%d° %d' %1.4f\"",
degrees, minutes, seconds];
latLabel.text = lat;
degrees = newLocation.coordinate.longitude;
decimal = fabs(newLocation.coordinate.longitude - degrees);
minutes = decimal * 60;
seconds = decimal * 3600 - minutes * 60;
NSString *longt = [NSString stringWithFormat:#"%d° %d' %1.4f\"",
degrees, minutes, seconds];
longLabel.text = longt;
}
How can I find the latitude and longitude and thereby find the address of the user?
EDIT:
Updated my version to Xcode 4.5. But still couldnot see the location ....?Y is it so?
please download this file
In the zip file I attached, there are 4 files:
LocationGetter.h and .m
PhysicalLocation.h and .m
you need to just import
#import "PhysicalLocation.h"
PhysicalLocation *physicalLocation = [[PhysicalLocation alloc] init];
[physicalLocation getPhysicalLocation];
in getPhysicalLocation at PhysicalLocation.m class
#pragma mark MKReverseGeocoder Delegate Methods
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
NSLog(#"%#",placemark);
objcntrAppDelegate = (yourappDeleger *)[[UIApplication sharedApplication]delegate];
objcntrAppDelegate.strCountry=placemark.country;
objcntrAppDelegate.strSuburb=placemark.subAdministrativeArea;
[[NSNotificationCenter defaultCenter] postNotificationName:#"ReceivedAddress" object:nil userInfo:nil];
[geocoder autorelease];
}
You get all of you neat lat, lng, current city, country, all that you need. Hope it helps you.
NOTE:- simulator gives incorrect result, you must test on device.
UPDATE
UpdatedDEMO
Change :
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
Now latitude and longitude should be obtained as float not int.
CLLocation *location = [locationManager location];
// Configure the new event with information from the location
CLLocationCoordinate2D coordinate = [location coordinate];
float longitude=coordinate.longitude;
float latitude=coordinate.latitude;
Find address of the user by latitude and longitude using CLGeocoder.
EDIT : Refer this link.
Related
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
// If it's a relatively recent event, turn off updates to save power
NSLog(#"%# locations",locations);
float Lat = _locationManager.location.coordinate.latitude;
float Long = _locationManager.location.coordinate.longitude;
NSLog(#"Lat : %f Long : %f",Lat,Long);
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(28.52171,77.2015457);
NSLog(#"center check %#",center);
CLCircularRegion *region = [[CLCircularRegion alloc] initWithCenter:center
radius:500
identifier:#"new region"];
BOOL doesItContainMyPoint = [region containsCoordinate:CLLocationCoordinate2DMake(Lat,Long)];
NSLog(#"success %hhd", doesItContainMyPoint);
}
the issue is ,here i m providing a static region for which i m checking (center)
but the requirement is, this region will take the lat n long of the riders and riders can vary in number
i hv all lat n long in an array of dictionary. First the driver will pick the first rider in the list and at that time i need the region of rider 1 location.
I m not getting any idea how to achieve this
if i do like this
for (NsMutableDictionary * dict in goersList)
{
rider_id=[dict valueForKey:#"trip_id"];
lat=[dict valueForKey:#"origin_lat"];
longi=[dict valueForKey:#"origin_long"];
}
then how will it know that the first region is to be monitored and after existing from that range i hv to check for second location
You can create dynamically regions and add them to monitoring.
for (NSDictionary *dict in [result valueForKey:#"Geofences"])
{
NSLog(#"%#",dict);
CLLocationCoordinate2D locationCoordinate=CLLocationCoordinate2DMake([[dict valueForKey:#"cLatitude"]doubleValue], [[dict valueForKey:#"cLongitude"]doubleValue]);
CLCircularRegion *circularRegion=[[CLCircularRegion alloc]initWithCenter:locationCoordinate radius:[[dict valueForKey:#"Radius"]doubleValue] identifier:[dict valueForKey:#"Name"]];
circularRegion.notifyOnEntry=YES;
circularRegion.notifyOnExit=YES;
[[AppDelegate sharedDelegate].locationManager startMonitoringForRegion:circularRegion];
NSLog(#"%#",[[[AppDelegate sharedDelegate] locationManager].monitoredRegions description]);
}
Here there are several regions are added to monitoring. You can add single at a time. i.e on selection of tableview.
And remove others using below code
for (CLRegion *monitored in [[AppDelegate sharedDelegate].locationManager monitoredRegions])
{
[[AppDelegate sharedDelegate].locationManager stopMonitoringForRegion:monitored];
}
I have two locations one is the driver and other is the rider.I have lat n long available for both.I want to hit an api when the driver enters in the geofence area of the riders location.
i went through QKGeofenceManager demo project:
using this i can provide lat n long and the radius to find geofence.
But the issue is do i have to update driver location every time in background and what condition should be applied so the the callback is made when the driver enters the geofence area of rider.If the ap is in background how will it handle everything.
Do i have to make any changes in appdelegate
- (NSArray *)geofencesForGeofenceManager:(QKGeofenceManager *)geofenceManager
{
NSArray *fetchedObjects = [self.fetchedResultsController fetchedObjects];
NSMutableArray *geofences = [NSMutableArray arrayWithCapacity:[fetchedObjects count]];
for (NSManagedObject *object in fetchedObjects) {
NSString *identifier = [object valueForKey:#"identifier"];
CLLocationDegrees lat = [[object valueForKey:#"lat"] doubleValue];
CLLocationDegrees lon = [[object valueForKey:#"lon"] doubleValue];
CLLocationDistance radius = [[object valueForKey:#"radius"] doubleValue];
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(lat, lon);
CLCircularRegion *geofence = [[CLCircularRegion alloc] initWithCenter:center radius:radius identifier:identifier];
[geofences addObject:geofence];
}
return geofences;
}
I found an alternative to achieve this task.
As my delegate method of Didenterlocation was not called,i applied another approach.
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
// If it's a relatively recent event, turn off updates to save power
NSLog(#"%# locations",locations);
float Lat = _locationManager.location.coordinate.latitude;
float Long = _locationManager.location.coordinate.longitude;
NSLog(#"Lat : %f Long : %f",Lat,Long);
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(28.58171,77.2915457);
NSLog(#"center check %#",center);
CLCircularRegion *region = [[CLCircularRegion alloc] initWithCenter:center
radius:500
identifier:#"new region"];
BOOL doesItContainMyPoint = [region containsCoordinate:CLLocationCoordinate2DMake(Lat,Long)];
NSLog(#"success %hhd", doesItContainMyPoint);
}
by keeping track of the current location,whenever the current location coordinates enter into the coordinates of the center region,you can fire a notification that the user has entered this particular region.
I have just completed compass app which will show distance between 2 coordinates.
Here is working code :
....
// created a timer to call locationUpdate method : 5sec
[NSTimer scheduledTimerWithTimeInterval:5 target: self selector: #selector(locationUpdate) userInfo: nil repeats: YES];
....
-(void)locationUpdate {
[locationManager startUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLoc
fromLocation:(CLLocation *)oldLoc
{
//To get the current location Latitude & Longitude.
float latitude = locationManager.location.coordinate.latitude;
float longitude = locationManager.location.coordinate.longitude;
startPoint = [[CLLocation alloc] initWithLatitude: latitude longitude: longitude ]; //Current Latitude and Longitude
endPoint = [[CLLocation alloc] initWithLatitude: 12.923670 longitude: 77.573496]; //Target Latitude and Longitude -----------------------------------> Need to come from database.
//To get the distance from the 2 coordinates in feet
CLLocationDistance distInMeter = [startPoint distanceFromLocation:endPoint];
//Lable veiw to update remaining distance.
if(distInMeter > 999.000f) {
self.labelLongLat.text = [NSString stringWithFormat: #"Remainig distance %.2f KM with Lat : %lf LAN %lf", distInMeter / 1000, latitude, longitude ];
}else
self.labelLongLat.text = [NSString stringWithFormat: #"Remainig distance %.2f M Lat : %lf LAN %lf" , distInMeter, latitude,longitude ];
}
My problem is while updating location for each 5sec, the coordinates varies a lot. That will result in Remaining distance calculation. Which is highly unstable!! How can I fix this?
Thanks in Advance,
The delegate method you are using is deprecated. You should use locationManager:didUpdateLocations:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *currentLocation = [locations lastObject];
endPoint = [[CLLocation alloc] initWithLatitude: 12.923670 longitude: 77.573496]; //Target Latitude and Longitude -----------------------------------> Need to come from database.
//To get the distance from the 2 coordinates in meters
CLLocationDistance distInMeter = [currentLocation distanceFromLocation:endPoint];
//Label view to update remaining distance.
if(distInMeter > 999 ) {
self.labelLongLat.text = [NSString stringWithFormat: #"Remaining distance %.2f Km with Lat : %lf LAN %lf", distInMeter / 1000, currentLocation.coordinate.latitude, currentLocation.coordinate.longitude ];
} else {
self.labelLongLat.text = [NSString stringWithFormat: #"Remaining distance %.2f m Lat : %lf LAN %lf" , distInMeter, currentLocation.coordinate.latitude, currentLocation.coordinate.longitude ];
}
}
The accuracy of your location can be affected by signal quality (tall buildings, indoor location etc). You can examine the horizontalAccuracy property of your location to see how accurate the position is. If the accuracy is low then you can defer updating your label. Beware that you may never get an accurate fix.
One strategy is to wait for an accuracy <20m or after 5 updates -
#property (nonatomic) NSInteger locationUpdates;
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
self.locationUpdates++;
CLLocation *currentLocation = [locations lastObject];
if (currentLocation.horizontalAccuracy < 20.0 || self.locationUpdates>5) {
endPoint = [[CLLocation alloc] initWithLatitude: 12.923670 longitude: 77.573496]; //Target Latitude and Longitude -----------------------------------> Need to come from database.
//To get the distance from the 2 coordinates in meters
CLLocationDistance distInMeter = [currentLocation distanceFromLocation:endPoint];
//Label view to update remaining distance.
if(distInMeter > 999 ) {
self.labelLongLat.text = [NSString stringWithFormat: #"Remaining distance %.2f Km with Lat : %lf LAN %lf", distInMeter / 1000, currentLocation.coordinate.latitude, currentLocation.coordinate.longitude ];
} else {
self.labelLongLat.text = [NSString stringWithFormat: #"Remaining distance %.2f m Lat : %lf LAN %lf" , distInMeter, currentLocation.coordinate.latitude, currentLocation.coordinate.longitude ];
}
}
}
I m working to get the Longitude and Latitude for current place and i m using the code
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation{
int degrees = newLocation.coordinate.latitude;
double decimal = fabs(newLocation.coordinate.latitude - degrees);
int minutes = decimal * 60;
double seconds = decimal * 3600 - minutes * 60;
lat = [NSString stringWithFormat:#"%d° %d' %1.4f\"",
degrees, minutes, seconds];
NSLog(#" Current Latitude : %#",lat);
degrees = newLocation.coordinate.longitude;
decimal = fabs(newLocation.coordinate.longitude - degrees);
minutes = decimal * 60;
seconds = decimal * 3600 - minutes * 60;
// longt = [NSString stringWithFormat:#"%d° %d' %1.4f\"",
// degrees, minutes, seconds];
longt = [NSString stringWithFormat:#"%d° %d' %1.4f\"",
degrees, minutes, seconds];
NSLog(#" Current Longitude : %#",longt);
}
and getting the:
Current Latitude : 37° 47' 9.0024"
Current Longitude : -122° 24' 23.1012"
But i want the Latitude and Longitude like that 13.233233 (mean in points). So how i can convert this in Longitude and Latitude in point ?Please help.
From the following answer Converting from longitude\latitude to Cartesian coordinates
x = R * cos(lat) * cos(lon)
y = R * cos(lat) * sin(lon)
z = R *sin(lat)
Where R is the approximate radius of earth (e.g. 6371KM).
In newLocation.coordinate.latitude and newLocation.coordinate.longitude, you have the values you want, just don't convert them.
why are you using this depreciated method use this method for getting location in iOS 7. Use this method
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
// location_updated = [locations lastObject];
// NSLog(#"updated coordinate are %#",location_updated);
float currentLocationLati = [[locations objectAtIndex:0] coordinate].latitude;
float currentLocationLong = [[locations objectAtIndex:0] coordinate].longitude;
}
By this methods you will find update latitude and longitude just use them don't convert them into degree
In my iOS app I've to track the distance from a a start point to my current location. I implemented this code:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *currentLocation = [locations lastObject];
CLLocation *startLocation = [locations firstObject];
[coordArray addObject:currentLocation];
float speed = currentLocation.speed * 3.6;
if (speed > 0) {
self.labelSpeed.text = [NSString stringWithFormat:#"%.2f Km/h", speed];
[speedArray addObject:[NSNumber numberWithFloat:speed]];
}
CLLocationDistance distance = [startLocation distanceFromLocation:currentLocation];
}
But when I try to use the app it doesn't get a distance. I need the distance to show it in a label and with distance I will calculate the number of steps by using this equation:
steps = distance / length of human step
I know that it's not accurate, but I can't use accelerometer, because it doesn't work while the display of the iPhone is not active. A person suggested me this solution. Why my code doesn't give me a distance?
The callback
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
does give you at least one location, and locations array hold sonly multiple objects if the location update was deferred before. To get the walking/driving distance, you have to store the initial location in a class variable or property. Then, when you want to calculate a distance, do as in your code above, but with the class variable that holds the initial location.
Check below code for getting distance:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
if ([coordArray count]>0) {
CLLocation *currentLocation = manager.location;
CLLocation *startLocation = [coordArray objectAtIndex:0];
[coordArray addObject:currentLocation];
float speed = currentLocation.speed * 3.6;
if (speed > 0) {
NSLog(#"\n speed:%#",[NSString stringWithFormat:#"%.2f Km/h", speed]);
}
CLLocationDistance distance = [startLocation distanceFromLocation:currentLocation];
if (distance>0) {
NSLog(#"Distance:%#",[NSString stringWithFormat:#"%lf meters",distance]);
}
}
else{
[coordArray addObject:manager.location];
}
}