Android中的距离计算?

时间:2012-11-05 08:29:44

标签: android distance google-places-api

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

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分: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