Latitude/Longitude distance question
I'm working on a tool that will find the closest latitude/longitude position from a list compared to the users current location. The list will be pretty long, and it will be running on a smart phone, so I'd like to make the calculations as开发者_运维技巧 simple and speedy as possible. From the threads I've read, calculating a fairly accurate distance between two latitude/longitude locations is a bit complicated, and I'm worried about speed. My question is, can I use something similar to the following to get a reasonable result for closest list position and use that?
$distance = sqrt((($firstLongitude-$secondLongitude)*($firstLongitude-$secondLongitude))+(($firstlLatitude-$secondLatitude)*($firstLatitude-$secondLatitude)));
I know the example is in PHP, but the logic should be evident. So my question is, will using the above logic to determine the closest location to the user from a list of lat/long locations give me correct results, or is there a potential issue I'm missing?
This app would only run for locations in the USA, if that makes any difference.
NOTE: I was also wondering if I could further simplify this and drop the sqrt part since I just want to see which is closer, and not how close it is.
The following is accurate if the points are within 10000 km of each other and if the earth is assumed to be spherical. Use d2 if you just want to compare distances. distance is the approximate distance in km.
deg = pi/180;
phi1 = lat1 * deg;
phi2 = lat2 * deg;
lam12 = (lon2 - lon1) * deg;
d2 = ( cos(phi1) * sin(phi2) - sin(phi1) * cos(phi2) * cos(lam12) )^2
+ ( cos(phi2) * sin(lam12) )^2;
a = 6371.009; // kilometers
distance = a * asin( sqrt( d2 ) );
For more accuracy you need to treat the earth as an ellipsoid; see my online geodesic calculator at http://geographiclib.sf.net/cgi-bin/Geod and the write-up at http://arxiv.org/abs/1102.1215.
No, The calculation will not show correct result. The result assume these lat/long are normal points but actually they are degrees. So you need to consider that in calculations as well.
Use the following formula. arithmetic formulas are not that heavy as compare to some network or UI activities
$1 = lat1
$2 = long1
$3 = lat2
$4 = long2
case when
($1 = $3 and $2 = $4) then 0
else 1609.344 * 60 * 1.1515 * (180 / pi()) * acos(sin($1 * pi() / 180) * sin($3 * pi() / 180) + cos($1 * pi() / 180) * cos($3 * pi() / 180) * cos(($2 - $4) * pi() / 180))
精彩评论