calculate distance between 2 coordinates iphone - best practice - iphone

I'm finishing an App in wish i need to show the user the distance between him and about 500 coordinates.
using the CLLocation method to calculate it, works well, but it takes about 1 minute in iPhone 4 to finish calculations for each location.
What is the best way to do it? Using span? Any other faster way?
Thanks all,
rui

I think Sahgal is right, here is some code, perhaps it will help you.
+(CGFloat)calculateDistanceBetweenSource:(CLLocationCoordinate2D)firstCoords andDestination:(CLLocationCoordinate2D)secondCoords
{
// this radius is in KM => if miles are needed it is calculated during setter of Place.distance
double nRadius = 6371;
// Get the difference between our two points
// then convert the difference into radians
double nDLat = (firstCoords.latitude - secondCoords.latitude)* (M_PI/180);
double nDLon = (firstCoords.longitude - secondCoords.longitude)* (M_PI/180);
double nLat1 = secondCoords.latitude * (M_PI/180);
double nLat2 = secondCoords.latitude * (M_PI/180);
double nA = pow ( sin(nDLat/2), 2 ) + cos(nLat1) * cos(nLat2) * pow ( sin(nDLon/2), 2 );
double nC = 2 * atan2( sqrt(nA), sqrt( 1 - nA ));
double nD = nRadius * nC;
NSLog(#"Distance is %f",nD);
return nD; // converts to miles or not (if en_) => implicit in method
}

I have seen the other answers, don't know if they are right, but I think there is a better solution:
(from documentation):
- (CLLocationDistance)distanceFromLocation:(const CLLocation *)location
You can use it like this:
- (CLLocationDistance) DistanceBetweenCoordinate:(CLLocationCoordinate2D)originCoordinate andCoordinate:(CLLocationCoordinate2D)destinationCoordinate {
CLLocation *originLocation = [[CLLocation alloc] initWithLatitude:originCoordinate.latitude longitude:originCoordinate.longitude];
CLLocation *destinationLocation = [[CLLocation alloc] initWithLatitude:destinationCoordinate.latitude longitude:destinationCoordinate.longitude];
CLLocationDistance distance = [originLocation distanceFromLocation:destinationLocation];
[originLocation release];
[destinationLocation release];
return distance;
}

Here is code for that..
-(NSString *)findDistanceBetweenTwoLatLon
{
int intEarthRadius = 3963;
double dblLat1 = DegreesToRadians(firstLatitude);
double dblLon1 = DegreesToRadians(firstLongitude);
double dblLat2 = DegreesToRadians(secondLatitude);
double dblLon2 = DegreesToRadians(secondLongitude);
float fltLat = dblLat2 - dblLat1;
float fltLon = dblLon2 - dblLon1;
double a = sin(fltLat/2) * sin(fltLat/2) + cos(dblLat2) * cos(dblLat2) * sin(fltLon/2) * sin(fltLon/2) ;
double c = 2 * atan2(sqrt(a), sqrt(1-a));
double d = intEarthRadius * c;
double dMeters = d * kOneMileMeters;
NSString *strDistance = [NSString stringWithFormat:#"%1.2f meters",dMeters];
return strDistance;
}
Define all this Macro..
and for degrees to radians
#define DegreesToRadians(degrees) (degrees * M_PI / 180)
where M_PI
#define M_PI 3.14159265358979323846264338327950288
#define kOneMileMeters 1609.344

You can try another approach.You can fetch the lat-long of both the points(assuming lat-long finding will not take that much time) and there are formulae to calculate the distance using lat-long.

Related

Calculate distance between 2 set of lon and lat

As my question states that's I am looking for a function/formula that can calculate a distance between two points. Now I have looked at example and found great functions but none of them seem to work they all return 0 when I supply 2 sets of points. Basically I will need to pass the function the following (lat1,lon1,lat2,lon2) and get back the distance. From this distance I can check a check if another point is close by.
UPDATE
Okay so I am now using the following function,
BEGIN
DECLARE pi, q1, q2, q3 , roundedVal FLOAT ;
DECLARE rads FLOAT DEFAULT 0;
SET pi = PI();
SET lat1 = lat1 * pi / 180;
SET lon1 = lon1 * pi / 180;
SET lat2 = lat2 * pi / 180;
SET lon2 = lon2 * pi / 180;
SET q1 = COS(lon1-lon2);
SET q2 = COS(lat1-lat2);
SET q3 = COS(lat1+lat2);
SET rads = ACOS( 0.5*((1.0+q1)*q2 - (1.0-q1)*q3) );
RETURN FORMAT((6371 * rads) , 1);
END
This works fine with Kilometres, but what I am looking for is meters. So I know I have the change the numbers in that function but which ones and what to. Any help ?
I have used this webiste in the past and it has worked for me. Has lots of useful formulas and gives examples in javascript.
http://www.movable-type.co.uk/scripts/latlong.html
I'd recommend you take a look at a spacial extention to MySQL.
http://dev.mysql.com/doc/refman/5.0/en/spatial-extensions.html
If you don't fancy that, this blog might have some use to you:
http://zcentric.com/2010/03/11/calculate-distance-in-mysql-with-latitude-and-longitude/
Try this query
$qry = "SELECT *,(((acos(sin((".$latitude."*pi()/180)) *
sin((`Latitude`*pi()/180))+cos((".$latitude."*pi()/180)) * cos((`Latitude`*pi()/180))*
cos(((".$longitude."- `Longitude`)*pi()/180))))*180/pi())*60*1.1515) as distance FROM
'MyTable` WHERE distance >= ".$distance."
apply this on the values
double theta = src_longitude - dest_longitude;
double min_distance = (Math.sin(Math.toRadians(src_latitude)) * Math.sin(Math.toRadians(dest_latitude))) +(Math.cos(Math.toRadians(src_latitude)) * Math.cos(Math.toRadians(dest_latitude)) * Math.cos(Math.toRadians(theta)));
min_distance = Math.acos(min_distance);
min_distance = Math.toDegrees(min_distance);
min_distance = min_distance * 60 * 1.1515 * 1.609344;

iPhone: calculate distance while walking using GPS

I want to calculate the distance that users cover while walking using GPS. For example a user taps the start button and starts to walk or run than when he done he taps stop. What will be the minimum distance user has to travel to get the different lat long?
How can we do it in IPhone, asume we take Lat, long after every 0.3 sec than in the last we have a list of points?
You could do this by calculating the distance between 2 points (latitude, longitude):
(I haven't tested it):
-(double)distanceBetweenCoordinate:(CLLocationCoordinate2D)c1 andCoordinate:(CLLocationCoordinate2D)c2 {
double long1 = degreesToRadians(c1.longitude);
double lat1 = degreesToRadians(90 - c1.latitude);
double long2 = degreesToRadians(c2.longitude);
double lat2 = degreesToRadians(90 - c2.latitude);
double gamma = fabs(long1 - long2);
if (gamma > M_PI) {
gamma = 2 * M_PI - gamma;
}
double result = cos(lat2) * cos(lat1) + sin(lat2) * sin(lat1) * cos(gamma);
return acos(result) * 6366.1977; // Kilometers
};
CGFloat degreesToRadians(CGFloat degrees) {
return degrees * M_PI / 180;
};
UPDATE: Use distanceFromLocation - Calculate distance between two points instead

Calculate new coordinate x meters and y degree away from one coordinate

I must be missing somthing out in the docs, I thought this should be easy...
If I have one coordinate and want to get a new coordinate x meters away, in some direction. How do I do this?
I am looking for something like
-(CLLocationCoordinate2D) translateCoordinate:(CLLocationCoordinate2D)coordinate
translateMeters:(int)meters
translateDegrees:(double)degrees;
Thanks!
Unfortunately, there's no such function provided in the API, so you'll have to write your own.
This site gives several calculations involving latitude/longitude and sample JavaScript code. Specifically, the section titled "Destination point given distance and bearing from start point" shows how to calculate what you're asking.
The JavaScript code is at the bottom of that page and here's one possible way to convert it to Objective-C:
- (double)radiansFromDegrees:(double)degrees
{
return degrees * (M_PI/180.0);
}
- (double)degreesFromRadians:(double)radians
{
return radians * (180.0/M_PI);
}
- (CLLocationCoordinate2D)coordinateFromCoord:
(CLLocationCoordinate2D)fromCoord
atDistanceKm:(double)distanceKm
atBearingDegrees:(double)bearingDegrees
{
double distanceRadians = distanceKm / 6371.0;
//6,371 = Earth's radius in km
double bearingRadians = [self radiansFromDegrees:bearingDegrees];
double fromLatRadians = [self radiansFromDegrees:fromCoord.latitude];
double fromLonRadians = [self radiansFromDegrees:fromCoord.longitude];
double toLatRadians = asin( sin(fromLatRadians) * cos(distanceRadians)
+ cos(fromLatRadians) * sin(distanceRadians) * cos(bearingRadians) );
double toLonRadians = fromLonRadians + atan2(sin(bearingRadians)
* sin(distanceRadians) * cos(fromLatRadians), cos(distanceRadians)
- sin(fromLatRadians) * sin(toLatRadians));
// adjust toLonRadians to be in the range -180 to +180...
toLonRadians = fmod((toLonRadians + 3*M_PI), (2*M_PI)) - M_PI;
CLLocationCoordinate2D result;
result.latitude = [self degreesFromRadians:toLatRadians];
result.longitude = [self degreesFromRadians:toLonRadians];
return result;
}
In the JS code, it contains this link which shows a more accurate calculation for distances greater than 1/4 of the Earth's circumference.
Also note the above code accepts distance in km so be sure to divide meters by 1000.0 before passing.
I found one way of doing it, had to dig to find the correct structs and functions. I ended up not using degrees but meters for lat and long instead.
Here's how I did it:
-(CLLocationCoordinate2D)translateCoord:(CLLocationCoordinate2D)coord MetersLat:(double)metersLat MetersLong:(double)metersLong{
CLLocationCoordinate2D tempCoord;
MKCoordinateRegion tempRegion = MKCoordinateRegionMakeWithDistance(coord, metersLat, metersLong);
MKCoordinateSpan tempSpan = tempRegion.span;
tempCoord.latitude = coord.latitude + tempSpan.latitudeDelta;
tempCoord.longitude = coord.longitude + tempSpan.longitudeDelta;
return tempCoord;
}
And of course, if I really need to use degrees in the future, it's pretty easy (I think...) to do some changes to above to get it to work like I actually asked for.
Using an MKCoordinateRegion has some issues—the returned region can be adjusted to fit since the two deltas may not exactly map to the projection at that latitude, if you want zero delta for one of the axes you are out of luck, etc.
This function uses MKMapPoint to perform coordinate translations which allows you to move points around in the map projection's coordinate space and then extract a coordinate from that.
CLLocationCoordinate2D MKCoordinateOffsetFromCoordinate(CLLocationCoordinate2D coordinate, CLLocationDistance offsetLatMeters, CLLocationDistance offsetLongMeters) {
MKMapPoint offsetPoint = MKMapPointForCoordinate(coordinate);
CLLocationDistance metersPerPoint = MKMetersPerMapPointAtLatitude(coordinate.latitude);
double latPoints = offsetLatMeters / metersPerPoint;
offsetPoint.y += latPoints;
double longPoints = offsetLongMeters / metersPerPoint;
offsetPoint.x += longPoints;
CLLocationCoordinate2D offsetCoordinate = MKCoordinateForMapPoint(offsetPoint);
return offsetCoordinate;
}
Nicsoft's answer is fantastic and exactly what I needed. I've created a Swift 3-y version which is a little more concise and can be called directly on a CLLocationCoordinate2D instance:
public extension CLLocationCoordinate2D {
public func transform(using latitudinalMeters: CLLocationDistance, longitudinalMeters: CLLocationDistance) -> CLLocationCoordinate2D {
let region = MKCoordinateRegionMakeWithDistance(self, latitudinalMeters, longitudinalMeters)
return CLLocationCoordinate2D(latitude: latitude + region.span.latitudeDelta, longitude: longitude + region.span.longitudeDelta)
}
}

iPhone Compass GPS Direction [duplicate]

I'm trying to develop an application that use the GPS and Compass of the iPhone in order to point some sort of pointer to a specific location (like the compass always point to the North). The location is fixed and I always need the pointer to point to that specific location no matter where the user is located. I have the Lat/Long coordinates of this location but not sure how can I point to that location using the Compass and the GPS... just like http://www.youtube.com/watch?v=iC0Xn8hY80w this link 1:20'
I write some code, however, it can't rotate right direction.
-(float) angleToRadians:(double) a {
return ((a/180)*M_PI);
}
-(void)updateArrow {
double alon=[longi doubleValue];//source
double alat=[lati doubleValue];//source
double blon=[pointlongi doubleValue];//destination
double blat=[pointlati doubleValue];//destination
float fLat = [self angleToRadians:alat];
float fLng = [self angleToRadians:alon];
float tLat = [self angleToRadians:blat];
float tLng = [self angleToRadians:blon];
float temp = atan2(sin(tLng-fLng)*cos(tLat),
cos(fLat)*sin(tLat)-sin(fLat)*cos(tLat)*cos(tLng-fLng));
double temp2= previousHeading;
double temp1=temp-[self angleToRadians:temp2];
/*I using this,but it can't rotate by :point even i change the coordinate
in CGPointMake */
Compass2.layer.anchorPoint=CGPointMake(0, 0.5);
[Compass2 setTransform:CGAffineTransformMakeRotation(temp1)];
/* Compass2 is a UIImageView like below picture I want to rotate it around
: point in image
^
|
|
|
:
|
*/
There is a standard "heading" or "bearing" equation that you can use - if you are at lat1,lon1, and the point you are interested in is at lat2,lon2, then the equation is:
heading = atan2( sin(lon2-lon1)*cos(lat2), cos(lat1)*sin(lat2) - sin(lat1)*cos(lat2)*cos(lon2-lon1))
This gives you a bearing in radians, which you can convert to degrees by multiplying by 180/π. The value is then between -180 and 180 degrees, so to get a standard compass bearing add 360 to any negative answers.
atan2 is a standard function related to arctan, that does the right thing for the four possible quadrants that your destination point could be in compared to where you are.
1) Get your current location (from the GPS)
2) Get the differences in latitude and longitude
3) use the atan2 method to get the angle
i.e. (WARNING: untested code)
CLLocation *targetLocation = [CLLocation alloc] initWithLatitude:1 longitude:2];
CLLocation *sourceLocation = <get from GPS>
double dx = [targetLocation coordinate].latitude - [sourceLocation coordinate].latitude;
double dy = [targetLocation coordinate].longitude - [sourceLocation coordinate].longitude;
double angle = atan2(dx, dy);
You might have to tweak that to get it to compile but the idea is there!
I did this some time ago, here are two different implementations. The first is similar to your approach, the second is without the trig math. The first is what I used in my app, but the second seemed to work as well, though doesn't appear to be as clean. You will need to also remember to offset this bearing based on north in your UI.
- (double) toRadian: (double) val
{
return val * (M_PI / 180);
}
// Convert to degrees from radians
- (double) toDegrees: (double) val
{
return val * 180 / M_PI;
}
// convert from a radian to a 360 degree format.
- (double) toBearing: (double) val
{
return ( (int)([self toDegrees: val]) + 360 ) % 360; // use mod to get the degrees
}
// Calculate the bearing based off of the passed coordinates and destination.
//
- (double) calcBearingWithLatitude:(CLLocationDegrees)latSource
latitude:(CLLocationDegrees)latDest
longitude:(CLLocationDegrees)lonSrc
longitude:(CLLocationDegrees)lonDest
{
double lat1 = [self toRadian:latSource];
double lat2 = [self toRadian:latDest];
double dLon = [self toRadian:(lonDest - lonSrc)];
double y = sin(dLon) * cos(lat2);
double x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
return [self toBearing:atan2(y, x)];
}
And the second.
// got this code from some forums and modified it, thanks for posting it coullis! Mostly here for reference on how to do this without sin and cos.
- (CLLocationDegrees) altCalcBearingWithLatitude:(CLLocationDegrees)latSource
latitude:(CLLocationDegrees)latDest
longitude:(CLLocationDegrees)lonSrc
longitude:(CLLocationDegrees)lonDest
{
CLLocationDegrees result;
// First You calculate Delta distances.
float dx = lonSrc - latSource;
float dy = lonDest - latDest;
// If x part is 0 we could get into division by zero problems, but in that case result can only be 90 or 270:
if (dx==0)
{
if (dy > 0)
result = 90;
else
result = 270;
}
else
{
result = [self toDegrees: atan(dy/dx)];
}
// This is only valid for two quadrants (for right side of the coordinate system) so modify result if necessary...
if (dx < 0)
result = result + 180;
// looks better if all numbers are positive (0 to 360 range)
if (result < 0)
result = result + 360;
// return our result.
return result;
}
Use this. You will have to subtract out your actual compass heading from the result of getHeadingForDirection to determine the proper relative heading. Return value is heading in radians.
-(float) angleToRadians:(float) a {
return ((a/180)*M_PI);
}
- (float) getHeadingForDirectionFromCoordinate:(CLLocationCoordinate2D)fromLoc toCoordinate:(CLLocationCoordinate2D)toLoc
{
float fLat = [self angleToRadians:fromLoc.latitude];
float fLng = [self angleToRadians:fromLoc.longitude];
float tLat = [self angleToRadians:toLoc.latitude];
float tLng = [self angleToRadians:toLoc.longitude];
return atan2(sin(tLng-fLng)*cos(tLat), cos(fLat)*sin(tLat)-sin(fLat)*cos(tLat)*cos(tLng-fLng));
}

iPhone SDK Point to a specific location [duplicate]

I'm trying to develop an application that use the GPS and Compass of the iPhone in order to point some sort of pointer to a specific location (like the compass always point to the North). The location is fixed and I always need the pointer to point to that specific location no matter where the user is located. I have the Lat/Long coordinates of this location but not sure how can I point to that location using the Compass and the GPS... just like http://www.youtube.com/watch?v=iC0Xn8hY80w this link 1:20'
I write some code, however, it can't rotate right direction.
-(float) angleToRadians:(double) a {
return ((a/180)*M_PI);
}
-(void)updateArrow {
double alon=[longi doubleValue];//source
double alat=[lati doubleValue];//source
double blon=[pointlongi doubleValue];//destination
double blat=[pointlati doubleValue];//destination
float fLat = [self angleToRadians:alat];
float fLng = [self angleToRadians:alon];
float tLat = [self angleToRadians:blat];
float tLng = [self angleToRadians:blon];
float temp = atan2(sin(tLng-fLng)*cos(tLat),
cos(fLat)*sin(tLat)-sin(fLat)*cos(tLat)*cos(tLng-fLng));
double temp2= previousHeading;
double temp1=temp-[self angleToRadians:temp2];
/*I using this,but it can't rotate by :point even i change the coordinate
in CGPointMake */
Compass2.layer.anchorPoint=CGPointMake(0, 0.5);
[Compass2 setTransform:CGAffineTransformMakeRotation(temp1)];
/* Compass2 is a UIImageView like below picture I want to rotate it around
: point in image
^
|
|
|
:
|
*/
There is a standard "heading" or "bearing" equation that you can use - if you are at lat1,lon1, and the point you are interested in is at lat2,lon2, then the equation is:
heading = atan2( sin(lon2-lon1)*cos(lat2), cos(lat1)*sin(lat2) - sin(lat1)*cos(lat2)*cos(lon2-lon1))
This gives you a bearing in radians, which you can convert to degrees by multiplying by 180/π. The value is then between -180 and 180 degrees, so to get a standard compass bearing add 360 to any negative answers.
atan2 is a standard function related to arctan, that does the right thing for the four possible quadrants that your destination point could be in compared to where you are.
1) Get your current location (from the GPS)
2) Get the differences in latitude and longitude
3) use the atan2 method to get the angle
i.e. (WARNING: untested code)
CLLocation *targetLocation = [CLLocation alloc] initWithLatitude:1 longitude:2];
CLLocation *sourceLocation = <get from GPS>
double dx = [targetLocation coordinate].latitude - [sourceLocation coordinate].latitude;
double dy = [targetLocation coordinate].longitude - [sourceLocation coordinate].longitude;
double angle = atan2(dx, dy);
You might have to tweak that to get it to compile but the idea is there!
I did this some time ago, here are two different implementations. The first is similar to your approach, the second is without the trig math. The first is what I used in my app, but the second seemed to work as well, though doesn't appear to be as clean. You will need to also remember to offset this bearing based on north in your UI.
- (double) toRadian: (double) val
{
return val * (M_PI / 180);
}
// Convert to degrees from radians
- (double) toDegrees: (double) val
{
return val * 180 / M_PI;
}
// convert from a radian to a 360 degree format.
- (double) toBearing: (double) val
{
return ( (int)([self toDegrees: val]) + 360 ) % 360; // use mod to get the degrees
}
// Calculate the bearing based off of the passed coordinates and destination.
//
- (double) calcBearingWithLatitude:(CLLocationDegrees)latSource
latitude:(CLLocationDegrees)latDest
longitude:(CLLocationDegrees)lonSrc
longitude:(CLLocationDegrees)lonDest
{
double lat1 = [self toRadian:latSource];
double lat2 = [self toRadian:latDest];
double dLon = [self toRadian:(lonDest - lonSrc)];
double y = sin(dLon) * cos(lat2);
double x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
return [self toBearing:atan2(y, x)];
}
And the second.
// got this code from some forums and modified it, thanks for posting it coullis! Mostly here for reference on how to do this without sin and cos.
- (CLLocationDegrees) altCalcBearingWithLatitude:(CLLocationDegrees)latSource
latitude:(CLLocationDegrees)latDest
longitude:(CLLocationDegrees)lonSrc
longitude:(CLLocationDegrees)lonDest
{
CLLocationDegrees result;
// First You calculate Delta distances.
float dx = lonSrc - latSource;
float dy = lonDest - latDest;
// If x part is 0 we could get into division by zero problems, but in that case result can only be 90 or 270:
if (dx==0)
{
if (dy > 0)
result = 90;
else
result = 270;
}
else
{
result = [self toDegrees: atan(dy/dx)];
}
// This is only valid for two quadrants (for right side of the coordinate system) so modify result if necessary...
if (dx < 0)
result = result + 180;
// looks better if all numbers are positive (0 to 360 range)
if (result < 0)
result = result + 360;
// return our result.
return result;
}
Use this. You will have to subtract out your actual compass heading from the result of getHeadingForDirection to determine the proper relative heading. Return value is heading in radians.
-(float) angleToRadians:(float) a {
return ((a/180)*M_PI);
}
- (float) getHeadingForDirectionFromCoordinate:(CLLocationCoordinate2D)fromLoc toCoordinate:(CLLocationCoordinate2D)toLoc
{
float fLat = [self angleToRadians:fromLoc.latitude];
float fLng = [self angleToRadians:fromLoc.longitude];
float tLat = [self angleToRadians:toLoc.latitude];
float tLng = [self angleToRadians:toLoc.longitude];
return atan2(sin(tLng-fLng)*cos(tLat), cos(fLat)*sin(tLat)-sin(fLat)*cos(tLat)*cos(tLng-fLng));
}