【问题标题】:How to sort distance in ascending order from latitude and longitude如何从纬度和经度按升序对距离进行排序
【发布时间】:2019-09-23 06:56:27
【问题描述】:

这里我通过脚本从服务器下载了地点数据,现在我想使用 Pythagore 按距离升序对Place 的列表进行排序

private class chargeur extends AsyncTask<Void, Void, List<Place>> {

        @Override
        protected List<Place> doInBackground(Void... voids) {
            List<Place> pl = new ArrayList<>();
            URL adresse = null;

            try {
                HttpsURLConnection cnx = Connecteur.connecter("get_all_places.php");
                BufferedReader B = new BufferedReader(new InputStreamReader(cnx.getInputStream()));
                String reponse = "";
                String lign = "";
                while ((lign = B.readLine())!=null) {
                    reponse+= lign;
                }

                JSONArray tab = new JSONArray(reponse);
                for (int i = 0; i<tab.length();i++) {
                    JSONObject obj = tab.getJSONObject(i);
                    String name = obj.getString("name");
                    String longitude = obj.getString("longitude");
                    String latitude = obj.getString("latitude");
                    Place p = new Place(name, longitude ,latitude);
                    pl.add(p);
                }
                return pl;
            } catch (Exception e) {}
        }
        // ...
}

【问题讨论】:

    标签: android sorting arraylist


    【解决方案1】:

    你可以做到的

    Collections.sort(pl, new Comparator<Place>() {
        public int compare(Place pl1, Place pl2) {
            // Write your logic here.
            return Math.sqrt(pl1.longitude * pl1.longitude + pl1.latitude * pl1.latitude) < 
                Math.sqrt(pl2.longitude * pl2.longitude + pl2.latitude * pl2.latitude);
        }});
    

    【讨论】:

    • 目标问题是使用毕达哥拉斯的方法,因为我数学不太好..
    • Math.sqrt(pl1.longitude * pl1.longitude + pl1.latitude * pl1.latitude) &lt; Math.sqrt(pl2.longitude * pl2.longitude + pl2.latitude * pl2.latitude)怎么样
    【解决方案2】:

    你可以使用hypot(),它返回到java.lang.Math类的2个点的距离:

    Collections.sort(pl, new Comparator<Place>() {
        public int compare(Place pl1, Place pl2) {
            Double d1 = Math.hypot(Double.parseDouble(p1.getLongitude()), Double.parseDouble(p1.getLatitude()));
            Double d2 = Math.hypot(Double.parseDouble(p2.getLongitude()), Double.parseDouble(p2.getLatitude()));
            return  d1.compareTo(d2);
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2014-01-22
      • 2013-06-28
      • 1970-01-01
      • 2015-01-06
      • 1970-01-01
      • 2013-05-04
      • 2013-04-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多