首页 > 代码库 > 根据坐标算距离,并排序

根据坐标算距离,并排序

//算距离
    public static double getDistance(double lng1,double lat1,double lng2,double lat2){
        double radLat1 = Math.toRadians(lat1);
        double radLat2 = Math.toRadians(lat2);
        double a = radLat1 - radLat2;
        double b = Math.toRadians(lng1) - Math.toRadians(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 * 6378137.0;// 取WGS84标准参考椭球中的地球长半径(单位:m)
        s = Math.round(s * 10000) / 10000;
        s = s/1000;
        return s;
    }

 排序:

//算距离
double latitude=Double.parseDouble(dto.getLatitude());//纬度
double longitude = Double.parseDouble(dto.getLongitude());//经度 distance = getDistance(longitude,latitude,Double.parseDouble(dataLongitude),Double.parseDouble(dataLatitude)); //查出所有距离,封装map //list1 为for循环每次查询出的数聚距离集合,初始值为null
Map<String,String> map = new HashMap<String, String>(); map.put("index", i+""); map.put("distance", distance+""); list1.add(map); //距离排序 Collections.sort(list1, new Comparator() { public int compare(Object a, Object b) { double one = Double.parseDouble(((Map<String,String>)a).get("distance")); double two = Double.parseDouble(((Map<String,String>)b).get("distance")); return (int) (one - two); } //排完距离的顺序,从新赋值index List<InterNodeInfoDto> list2 = new ArrayList<InterNodeInfoDto>(); for(Map<String,String> temp : list1){ list2.add(list.get(Integer.parseInt(temp.get("index")))); }

 

根据坐标算距离,并排序