-2

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

私有字符串 getDistance(最终字符串开始,最终字符串结束){

           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 公里,而不是实际距离。

4

2 回答 2

1

试试这个链接,它将毫无疑问地帮助你。

于 2012-11-05T08:38:41.160 回答
0

您不必查询谷歌地图来获取两个地方之间的距离。如果您知道这两个地方的纬度和经度,您就可以构建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
于 2012-11-05T08:41:17.217 回答