CLLocation *useOne = [[CLLocation alloc] initWithLatitude:40.074744 longitude:116.240179];
CLLocation *useTwo = [[CLLocation alloc] initWithLatitude:40.079106 longitude:116.243469];
CLLocationDistance distance = [useOne distanceFromLocation:useTwo];
NSLog(#"%d",distance);
But I got the result is "distance=1921570242" metres. absolutely this result was incorrect.
So where am I wrong?
Your calculations are correct, but the way you print is wrong. CLLocationDistance is a double, so format specifier in NSLog should be %f (%d is used for integers):
NSLog(#"%f",distance);
Related
i am working on a project in which i have to show the distance of multiple locations from user's locations. locations are based on latitude and longitude.
i am using the following code to get the distance between two locations is shows nearly same distance
CLLocation *locA = [[CLLocation alloc] initWithLatitude:28.6379 longitude: 77.2432];
CLLocation *locB = [[CLLocation alloc] initWithLatitude:28.6562 longitude:77.2410];
CLLocationDistance distance = [locA distanceFromLocation:locB];
NSLog(#"Distance is %f",distance);
float i = distance/1000;
NSLog(#"distance between two places is %f KM", i);
but now i am struct to get the distance of multiple locations from my location: locaA.
for example i take NSarray for latitude and longitude as
NSArray * latArray = [[NSArray alloc]initWithObjects:#"28.6129",#"28.6020",#"28.5244", nil];
NSArray * longArray = [[NSArray alloc]initWithObjects:#"77.2295",#"77.2478",#"77.1855", nil];
Please help me to resolve it
Take locaA as user's location
You can use below method to find distance
#define DEG2RAD(degrees) (degrees * 0.01745327)
double currentLatitudeRad = DEG2RAD(currentLatitude);
double currentLongitudeRad = DEG2RAD(currentLongitude);
double destinationLatitudeRad = DEG2RAD(destinationLatitude);
double destinationLongitudeRad = DEG2RAD(destinationLongitude);
double distance = acos(sin(currentLatitudeRad) * sin(destinationLatitudeRad) + cos(currentLatitudeRad) * cos(destinationLatitudeRad) * cos(currentLongitudeRad - destinationLongitudeRad)) * 6880.1295896;
Here, currentLatitude and currentLongitude is user's location. destinationLatitude and destinationLongitude is each object from your array "latArray" and "longArray" which you can iterate via for loop. distance is the distance between user's location and locations in array. Obtained distance will be in kilometres.
CLLocation *currentLocation = ... // This is a reference to your current location as a CLLocation
NSArray *arrayOfOtherCLLocationObjects = ... // This is an array that contains all of the other points you want to calculate the distance to as CLLocations
NSMutableArray *distancesFromCurrentLocation = [[NSMutableArray alloc] initWithCapacity:arrayOfOtherCLLocationObjects.count]; // We will add all of the calculated distances to this array
for (CLLocation *location in arrayOfOtherCLLocationObjects) // Iterate through each location object
{
CLLocationDistance distance = [location distanceFromLocation:currentLocation]; // Calculate distance
[distancesFromCurrentLocation addObject:#(distance)]; // Append distance to array. You need to wrap the distance object as an NSNumber so you can append it to the array.
}
// At this point, you have the distance for each location point in the array distancesFromCurrentLocation
Swift version:
let currentLocation: CLLocation = //current location
let otherLocations: [CLLocation] = //the locations you want to know their distance to currentLocation
let distances = otherLocations.map { $0.distanceFromLocation(currentLocation) }
I have an array full of longitudes and latitudes. I have two double variables with my users location. I'd like to test the distance between my user's locations against my array to see which location is the closest. How do I do this?
This will get the distance between 2 location but stuggeling to understand
how I'd test it against an array of locations.
CLLocation *startLocation = [[CLLocation alloc] initWithLatitude:userlatitude longitude:userlongitude];
CLLocation *endLocation = [[CLLocation alloc] initWithLatitude:annotation.coordinate.latitude longitude:annotation.coordinate.longitude];
CLLocationDistance distance = [startLocation distanceFromLocation:endLocation];
You just need to iterate through the array checking the distances.
NSArray *locations = //your array of CLLocation objects
CLLocation *currentLocation = //current device Location
CLLocation *closestLocation;
CLLocationDistance smallestDistance = DOUBLE_MAX;
for (CLLocation *location in locations) {
CLLocationDistance distance = [currentLocation distanceFromLocation:location];
if (distance < smallestDistance) {
smallestDistance = distance;
closestLocation = location;
}
}
At the end of the loop you will have the smallest distance and the closest location.
#Fogmeister
I think this is a mistake which must be set right about DBL_MAX and an assignment.
First : Use DBL_MAX instead of DOUBLE_MAX.
DBL_MAX is a #define variable in math.h.
It's the value of maximum representable finite floating-point (double) number.
Second : In your condition, your assignment is wrong :
if (distance < smallestDistance) {
distance = smallestDistance;
closestLocation = location;
}
You must do :
if (distance < smallestDistance) {
smallestDistance = distance;
closestLocation = location;
}
The difference is that will be assign distance value into smallestDistance, and not the opposite.
The final result :
NSArray *locations = //your array of CLLocation objects
CLLocation *currentLocation = //current device Location
CLLocation *closestLocation;
CLLocationDistance smallestDistance = DBL_MAX; // set the max value
for (CLLocation *location in locations) {
CLLocationDistance distance = [currentLocation distanceFromLocation:location];
if (distance < smallestDistance) {
smallestDistance = distance;
closestLocation = location;
}
}
NSLog(#"smallestDistance = %f", smallestDistance);
Can you confirm that is correct ?
How to create MKCoordinateRegion .
NSString *latitudeString = [locationString substringToIndex:startRange.location];
NSString *longtitudeString = [locationString substringWithRange:NSMakeRange(startRange.location+2,((endRange.location-1)-(startRange.location+2)))];
CLLocationCoordinate2D coord = CLLocationCoordinate2DMake((int)latitudeString, (int)longtitudeString);
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(coord, 500, 500);`
I get the error "Invalid Region center:+392128672.00000000, +392128704.00000000 span:+0.00448287, -0.01195557"
Remove the type casting. Use below code.
CLLocationCoordinate2D coord = CLLocationCoordinate2DMake([latitudeString doubleValue], [longtitudeString doubleValue]);
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(coord, 500, 500);
If you store your latitude and longitude in a string like this:
NSString *latitudeString = #"12.2323";
You should convert it to a float, like this:
CGFloat latitude = [latitudeString floatValue];
And after that, you can this in your
CLLocationCoordinate2DMake
method, it should work. And the problem comes from, that the latitude can only between -90 and 90, the longitude between -180 and 180 (degree), and your numbers are way bigger than that.
I have latitude and longitude values as string and want to convert it to corelocation. My main intension is to calculate the distance between the user's current location (returned by the device) and the location returned from the server.
calculate distance using lat and long.. This post helped me to find distance between two locations.
Which of the following will be the best way?
Should I convert string to core location and calculate distance
or
should i convert the device location to string and calculate distance.
Create and object like so:
CLLocation *locA = [[CLLocation alloc] initWithLatitude:lat1 longitude:long1];
lat1 / long2 are of type CLLocationDegrees which is a typedef of a double, representing the point in degrees.
Convert your lat / long to doubles and pass them in, like so:
CLLocation *locA = [[CLLocation alloc] initWithLatitude:[#"" doubleValue] longitude:[#"" doubleValue] ];
The above code was in the example you linked to, you could have very easily google'd the object and it would have brought you to the doc online.
EDIT:
As per Volker's suggestion, if you are getting numbers from a server, there is a possibility of localisation issues, where some local's use a decimal: 46.000 and others use a comma 46,000.
Something like this would be better:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setLocale:[NSLocale currentLocale]];
NSNumber *temp = [formatter numberFromString:#""];
[temp doubleValue];
I'm using the reverse geocoder and I want to save info into a SQLite database but I need the latitude and longitude set by the user but it's not being passed.
I've got two doubles var called latitude and longitude and when I execute this code below, it uses "random" doubles:
CLLocation *locate = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
CLGeocoder *geoCoderCL = [[CLGeocoder alloc] init];
[geoCoderCL reverseGeocodeLocation: locate completionHandler:
^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
Controller *mController = [[Controller alloc] init];
MyObject *newposition = [[Meeting alloc]init];
[newposition setLatitude:latitude];
[newposition setLongitude:longitude];
[newposition setMName:[NSString stringWithFormat:#"%# %#",placemark.thoroughfare,placemark.subThoroughfare]];
NSLog(#"%# %#",placemark.thoroughfare,placemark.subThoroughfare);
[mController createRecentPoint:newposition];
[mController release];
[newposition release];
}];
How is supposed to do this? Thanks.
Use the following to derive the latitude and longitude from a CLPlacemark object.
CLLocationDegrees latitude = placemark.location.coordinate.latitude;
CLLocationDegrees longitude = placemark.location.coordinate.longitude;
location is a CLLocation object. coordinate is a CLLocationCoordinate2D struct and latitude and longitude are CLLocationDegrees (which is just a typdef'd double).