【问题标题】:Distance Calculations in Android? [closed]Android中的距离计算? [关闭]
【发布时间】:2013-06-07 02:48:09
【问题描述】:

我对 android 谷歌地图非常陌生,我编写了用于查找两个地方之间的距离的代码:

private String getDistance(final String start, final String end) {

           new Thread(new Runnable() {
                @Override
                public void run() {
     float distance = 0.0f;
               StringBuffer url = new StringBuffer("http://maps.googleapis.com/maps/api/directions/json?origin=");
                 url.append(start.replace(" ", "").trim().toString());
                 url.append("&destination=");
                 url.append(end.replace(" ", "").trim().toString());
                 url.append("&mode=transit");
                 url.append("&language=en-EN");
                 url.append("&sensor=false");



                 DefaultHttpClient httpClient = new DefaultHttpClient();
                 HttpGet httpGet = new HttpGet(url.toString());
                 HttpResponse httpResponse = httpClient.execute(httpGet);
                 HttpEntity httpEntity = httpResponse.getEntity();
                 String line = EntityUtils.toString(httpEntity);

                 JSONObject jsonObject = new JSONObject(line);
                 JSONArray jsonarray = jsonObject.getJSONArray("routes").getJSONObject(0).getJSONArray("legs");

                 for (int i = 0; i < jsonarray.length(); i++) {
                     JSONObject obj = jsonarray.getJSONObject(i);
                     distance  = Float.valueOf(obj.getJSONObject("distance").getString("text").replace("km", ""));
                     System.out.println("Distance == " + obj.getJSONObject("distance").getString("text").replace("km", ""));
                 }


              BigDecimal   kmVal = BigDecimal.valueOf(distance);
              System.out.println("===========distance=============="+kmVal);

            } catch (Exception e) {
                e.printStackTrace();
            }
                }
                }).start();

            return distance  ;

    }

我得到的距离相差 30 公里。我比实际距离多了 30 公里。

【问题讨论】:

  • 您应该做的第一件事是将代码中的不同职责分开......获取数据和计算距离应该是单独的关注点。然后尝试在调试器中运行
  • 好的,我怎样才能得到正确的距离?
  • 通过分解问题和调试...就像我刚才提到的...
  • 我担心我的距离以公里为单位,但额外距离为 30k?
  • 我担心你没有听取建议。

标签: android distance google-places-api


【解决方案1】:
【解决方案2】:

您不必查询谷歌地图来获得两地之间的距离。如果你知道这两个地方的纬度和经度,你可以构造 Location 对象并使用它的 distanceTo() 方法,它会给你以米为单位的确切距离。

Location from = new Location("");
from.setLatitude(yourStartLatitude);
from.setLongitude(yourStartLongitude);

Location to = new Location("");
to.setLatitude(yourEndLatitude);
to.setLongitude(yourEndLongitude);

float distance = from.distanceTo(to); // The distance in meters

【讨论】:

  • 由此我得到 514625.25 这些类型的值?
  • 表示 514625 m = 514,6 km
  • 这不是实际距离假设海得拉巴到钦奈是 620 公里,但基于此错误?
  • 这是直线距离,不是道路上的距离。如果这就是你所追求的,你不应该使用这种方法。如果您只想知道确切的距离,那么就是这样。
猜你喜欢
  • 2023-03-04
  • 2012-04-02
  • 1970-01-01
  • 1970-01-01
  • 2021-01-17
  • 2010-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多