计算地图上两点间的距离
package com.fhc.modules.api.utils;
import java.text.ParseException;
/**
* 两点间距离计算
*/
public class LocationUtil {
private static double EARTH_RADIUS =6378.137;
/**
* 角度弧度计算公式rad()
* 360度=2π π=Math.PI
* x度 = x*π/360 弧度
*
* @param d
* @return
*/
private static double rad(double d) {
return d * Math.PI /180.0;
}
/**
* 根据两点间经纬度坐标(double值),计算两点间距离,单位为米
*
* @param lng1 经度1
* @param lat1 纬度1
* @param lng2 经度2
* @param lat2 纬度2
* @return
*/
public static double getDistance(double lng1, double lat1, double lng2, double lat2) {
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 *10000d) /10000d;
s = s *1000;
return s;
}
/**
* test
*/
public static void main(String[] args)throws ParseException {
double xwbg =getDistance(114.415686, 38.045362, 114.518596, 38.049113);
System.out.println("西王地铁站到北国地铁站" + xwbg /1000 +"公里");
double xwbf =getDistance(114.415686, 38.045362, 114.593012, 38.050477);
System.out.println("西王地铁站到白佛地铁站" + xwbf /1000 +"公里");
}
}