This is a big fat commentary on the code posted in @Sven Marnach's (currently accepted) answer.
Original code from the zip project site, indented by me:
from math import * def calcDist(lat_A, long_A, lat_B, long_B): distance = (sin(radians(lat_A)) * sin(radians(lat_B)) + cos(radians(lat_A)) * cos(radians(lat_B)) * cos(radians(long_A - long_B))) distance = (degrees(acos(distance))) * 69.09 return distance
Code sent by Sven:
from math import sin, cos, radians, degrees def calc_dist(lat_a, long_a, lat_b, long_b): lat_a = radians(lat_a) lat_b = radians(lat_b) distance = (sin(lat_a) * sin(lat_b) + cos(lat_a) * cos(lat_b) * cos(long_a - long_b)) return degrees(acos(distance)) * 69.09
Problem 1: DO NOT START : acos needs to be imported
Problem 2: INCORRECT ANSWERS : it is necessary to convert the difference of longitude to radians in the second last line
Task 3: The variable name "distance" is an extreme misnomer. This value is actually equal to the cos of the angle between the two lines from the center of the earth to the input points. Go to "cos_x"
Problem 4: There is no need to convert the angle x to degrees. Just multiply x by the radius of the earth in the selected units (km, nm or "charter miles")
After fixing all this, we get:
from math import sin, cos, radians, acos # http:
Note. After eliminating problems 1 and 2, this is the "spherical law of cosines", as is usually implemented. This is normal for applications such as the "distance between two US zip codes."
Caution 1: it is not accurate for small distances, for example, from your front door to the street, so much that it can give a non-zero distance or cause an exception (cos_x> 1.0) if the two points are identical; this situation can be specially dressed.
Caution 2: If two points are antipodes (a direct path passes through the center of the earth), it can throw an exception (cos_x <-1.0). Anyone who is worried about this can check cos_x before executing acos (cos_x).
Example:
SFO (37.676, -122.433) to NYC (40.733, -73.917)
calcDist β 2570.7758043869976
calc_dist β 5038.599866130089
calc_dist_fixed β 2570.9028268899356
US Government Website (http://www.nhc.noaa.gov/gccalc.shtml) β 2569
This site (http://www.timeanddate.com/worldclock/distanceresult.html?p1=179&p2=224), from which I got the coordinates of SFO and NYC, β 2577