C语言版:
#include <stdio.h>
#include <math.h>
#define PI 3.1415926
#define EARTH_RADIUS 6366000 //地球近似半径(mi)
//计算距离
double get_distance(double lat_a, double lng_a, double lat_b, double lng_b)
{
double pk = 180 / PI;
double a1 = lat_a / pk;
double a2 = lng_a/pk;
double b1 = lat_b /pk;
double b2 = lng_b/pk;
double t1 = cos(a1) * cos(a2) * cos(b1) * cos(b2);
double t2 = cos(a1) * sin(a2) * cos(b1) * sin(b2);
double t3 = sin(a1) * sin(b1);
double tt = acos(t1 + t2 + t3);
double distance = EARTH_RADIUS * tt;
//printf("distance:%f\n", distance);
return distance;
}
Python版:
def get_distance(lat1, lng1, lat2, lng2):
'''
'''
earth_radius = 6366000
pk = 180 / 3.1415926
a1 = lat1 / pk
a2 = lng1 / pk
b1 = lat2 / pk
b2 = lng2 / pk
t1 = math.cos(a1) * math.cos(a2) * math.cos(b1) * math.cos(b2)
t2 = math.cos(a1) * math.sin(a2) * math.cos(b1) * math.sin(b2)
t3 = math.sin(a1) * math.sin(b1)
tt = math.acos(t1 + t2 + t3)
return int(round(earth_radius * tt))
print (get_distance(31.234823, 121.533489, 31.233588, 121.555084))
2056