1.数据库方式
drop function if exists getDistance;
DELIMITER $$
CREATE DEFINER=`root`@`localhost` FUNCTION `getDistance`(
lon1 double
,lat1 double
,lon2 double
,lat2 double
) RETURNS double
begin
declare d double;
declare radius double;
set radius = 63781.37;
set d = (2*ATAN2(SQRT(SIN((lat1-lat2)*PI()/180/2)
*SIN((lat1-lat2)*PI()/180/2)+
COS(lat2*PI()/180)*COS(lat1*PI()/180)
*SIN((lon1-lon2)*PI()/180/2)
*SIN((lon1-lon2)*PI()/180/2)),
SQRT(1-SIN((lat1-lat2)*PI()/180/2)
*SIN((lat1-lat2)*PI()/180/2)
+COS(lat2*PI()/180)*COS(lat1*PI()/180)
*SIN((lon1-lon2)*PI()/180/2)
*SIN((lon1-lon2)*PI()/180/2))))*radius;
return d;
end
$$
DELIMITER ;
2.java程序方式
public final class GpsHelper {
private static final double EARTH_RADIUS = 6378.137;
private static double rad(double d){
return d * Math.PI / 180.0;
}
public static double getDistance(double lat1,double lng1, double lat2,double lng2){
double radLat1 = rad(lat1);
double radLat2 = rad(lat2);
double a = radLat1 - radLat2;
double b = rad(lng1) - rad(lng2);
double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
s = s * EARTH_RADIUS;
s = Math.round(s * 10000) / 10000;
return s;
}
}