利用Java计算经纬度距离工具类

利用Java计算经纬度距离工具类


import java.math.BigDecimal;

/**
* @Description:  经纬度距离工具类
* @Param:
* @return:
* @Author: yzz
* @Date: 2020/4/18
*/
public class DistanceUtil {
    private static double EARTH_RADIUS = 6378.137;

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 通过经纬度获取距离(单位:千米)
     * @param lat1
     * @param lng1
     * @param lat2
     * @param lng2
     * @return
     */
    public static BigDecimal 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 * 10000d) / 10000d;
        BigDecimal bd = new BigDecimal(s);
        bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);	//保留小数点后两位
        return bd;
    }
}

这个是利用距离从小到大排序
(其中BasanInfoVO是你的实体类)

Collections.sort(list, new Comparator<BasanInfoVO>() {//根据距离排序
                    public int compare(BasanInfoVO o1, BasanInfoVO o2) {
                        return o1.getDistance().compareTo(o2.getDistance());
                    }
                });

从以上可以通过经纬度获取距离从而进行排序!

											技术交流联系qq:930210782
发布了2 篇原创文章 · 获赞 0 · 访问量 14

猜你喜欢

转载自blog.csdn.net/weixin_43879088/article/details/105723308
今日推荐