一、java代码
public static final double DEGREES_TO_RADIANS = Math.PI / 180.0;
public static final double RADIANS_TO_DEGREES = 180.0 / Math.PI;
//地球半径
public static final double EARTH_MEAN_RADIUS_KM = 6371.009;
//地球直径
private static final double EARTH_MEAN_DIAMETER = EARTH_MEAN_RADIUS_KM * 2;
/***
* 距离半径计算方式
* @param lat1 中心点经纬度
* @param lng1
* @param lat2 目标经纬度
* @param lng2
* @return 两坐标的距离 单位千米
*/
public static double getDistance(Double lng1,Double lat1,Double lng2,Double lat2) {
//计算经纬度
double latRad = lat2 * DEGREES_TO_RADIANS;
double lonRad = lng2 * DEGREES_TO_RADIANS;
//计算经纬度的差
double diffX = lat1 * DEGREES_TO_RADIANS - latRad;
double diffY = lng1 * DEGREES_TO_RADIANS - lonRad;
//计算正弦和余弦
double hsinX = Math.sin(diffX * 0.5);
double hsinY = Math.sin(diffY * 0.5);
double latCenterRad_cos = Math.cos(lat1 * DEGREES_TO_RADIANS);
double h = hsinX * hsinX + (latCenterRad_cos * Math.cos(latRad) * hsinY * hsinY);
return (EARTH_MEAN_DIAMETER * Math.atan2(Math.sqrt(h), Math.sqrt(1 - h)));
}
二、mysql
6378.138 * 2 * ASIN( SQRT( POW( SIN( ( #{query.lat} * PI() / 180 - b.lat * PI() / 180 ) / 2 ), 2 ) + COS(#{query.lat}* PI() / 180) * COS(b.lat * PI() / 180) * POW( SIN( ( #{query.lng} * PI() / 180 -b.lng * PI() / 180 ) / 2 ), 2 ) ) )*1000 AS distance