如何通过道路计算两个位置之间的距离?

时间:2019-10-29 17:44:06

标签: android android-studio

我想通过道路/类似驾驶模式来计算两个位置之间的距离。 这是我的代码,但错误来自“响应= client.execute(httppost);”。这条线。请帮助我。

private double getDistance(double latFrom, double lngFrom,double latTo,double lngTo) {
    StringBuilder stringBuilder = new StringBuilder();
    String apikey="API KEY";
    Double dist = 0.0;
    try {


        String url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + latFrom + "," + lngFrom + "&destination=" + latTo + "," + lngTo + "&mode=driving&sensor=false"+"&key="+apikey;

        HttpPost httppost = new HttpPost(url);

        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        stringBuilder = new StringBuilder();


        response = client.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }
    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }

    JSONObject jsonObject = new JSONObject();
    try {

        jsonObject = new JSONObject(stringBuilder.toString());
        JSONArray array = jsonObject.getJSONArray("routes");
        JSONObject routes = array.getJSONObject(0);
        JSONArray legs = routes.getJSONArray("legs");
        JSONObject steps = legs.getJSONObject(0);
        JSONObject distance = steps.getJSONObject("distance");
        Log.i("Distance", distance.toString());
        dist = Double.parseDouble(distance.getString("text").replaceAll("[^\\.0123456789]","") );

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return dist;
}

1 个答案:

答案 0 :(得分:1)

解决您的错误的方法是在后台线程上执行所有网络操作。例如,在与主线程不同的线程上使用AsyncTaskRunnable

要详细说明我的答案,您的网络通话将以您的doInBackground()的{​​{1}}方法进行。

永远不要在主线程上执行网络操作,因为网络调用会阻止操作,并会严重阻碍您的UI响应。