【问题标题】:Getting distance from Google Direction API in Android在 Android 中与 Google Direction API 保持距离
【发布时间】:2014-01-07 19:13:29
【问题描述】:

http://maps.googleapis.com/maps/api/directions/json?origin=-20.291825,57.448668&destination=-20.179724,57.613463&sensor=false&mode=%22DRIVING%22

例如此链接生成以下内容:

"routes" : [
      {
         "bounds" : {
            "northeast" : {
               "lat" : -20.1765204,
               "lng" : 57.6137001
            },
           "southwest" : {
               "lat" : -20.2921672,
               "lng" : 57.4472155
            }
         },
         "copyrights" : "Map data ©2014 Google",
         "legs" : [
            {
               "distance" : {
                  "text" : "24.6 km",
                  "value" : 24628
               },

我只想提取距离并在android中显示

【问题讨论】:

标签: android distance google-directions-api


【解决方案1】:

要从 Google 地图获取距离,您可以使用 Google Directions API 和 JSON 解析器来检索距离值。

样本方法

private double getDistanceInfo(double lat1, double lng1, String destinationAddress) {
            StringBuilder stringBuilder = new StringBuilder();
            Double dist = 0.0;
            try {

            destinationAddress = destinationAddress.replaceAll(" ","%20");    
            String url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + latFrom + "," + lngFrom + "&destination=" + latTo + "," + lngTo + "&mode=driving&sensor=false";

            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;
        }

有关参数的详细信息以及可用的不同选项的更多详细信息,请参阅此。

https://developers.google.com/maps/documentation/directions/

【讨论】:

  • @Prem 我认为这是一个 GET 请求而不是一个 POST 请求。
  • 非常适合我。您甚至可以通过这种方式获取持续时间: JSONObject duration= steps.getJSONObject("duration");
  • 为什么你没有传递参数 "&key=YOUR_API_KEY" ?
【解决方案2】:
public class ApiDirectionsAsyncTask extends AsyncTask<URL, Integer, StringBuilder> {

    private static final String TAG = makeLogTag(ApiDirectionsAsyncTask.class);

    private static final String DIRECTIONS_API_BASE = "https://maps.googleapis.com/maps/api/directions";
    private static final String OUT_JSON = "/json";

    // API KEY of the project Google Map Api For work
    private static final String API_KEY = "YOUR_API_KEY";

    @Override
    protected StringBuilder doInBackground(URL... params) {
        Log.i(TAG, "doInBackground of ApiDirectionsAsyncTask");

        HttpURLConnection mUrlConnection = null;
        StringBuilder mJsonResults = new StringBuilder();
        try {
            StringBuilder sb = new StringBuilder(DIRECTIONS_API_BASE + OUT_JSON);
            sb.append("?origin=" + URLEncoder.encode("Your origin address", "utf8"));
            sb.append("&destination=" + URLEncoder.encode("Your destination address", "utf8"));
            sb.append("&key=" + API_KEY);

            URL url = new URL(sb.toString());
            mUrlConnection = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(mUrlConnection.getInputStream());

            // Load the results into a StringBuilder
            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1){
                mJsonResults.append(buff, 0, read);
            }

        } catch (MalformedURLException e) {
            Log.e(TAG, "Error processing Distance Matrix API URL");
            return null;

        } catch (IOException e) {
            System.out.println("Error connecting to Distance Matrix");
            return null;
        } finally {
            if (mUrlConnection != null) {
                mUrlConnection.disconnect();
            }
        }

        return mJsonResults;
    }
}

希望对你有帮助!

【讨论】:

    【解决方案3】:

    只需检查以下链接。您可能会对此有所了解并自行尝试。

    http://about-android.blogspot.in/2010/03/sample-google-map-driving-direction.html

    您也可以使用 Google 距离矩阵 API

    https://developers.google.com/maps/documentation/distancematrix/

    【讨论】:

      【解决方案4】:
      String url = getDirectionsUrl(pickupLatLng, dropLatLng);
      new GetDisDur().execute(url);
      

      使用 latlng 创建 URL

      private String getDirectionsUrl(LatLng origin, LatLng dest) {
      
              String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
      
              String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
      
              String sensor = "sensor=false";
      
              String mode = "mode=driving";
      
              String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode;
      
              String output = "json";
      
              return "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
          }
      

      GetDisDur

      private class GetDisDur extends AsyncTask<String, String, String> {
      
              @Override
              protected String doInBackground(String... url) {
      
                  String data = "";
      
                  try {
                      data = downloadUrl(url[0]);
                  } catch (Exception e) {
                      Log.d("Background Task", e.toString());
                  }
                  return data;
              }
      
              @Override
              protected void onPostExecute(String result) {
                  super.onPostExecute(result);
      
                  try {
                      JSONObject jsonObject = new JSONObject(result);
      
                      JSONArray routes = jsonObject.getJSONArray("routes");
      
                      JSONObject routes1 = routes.getJSONObject(0);
      
                      JSONArray legs = routes1.getJSONArray("legs");
      
                      JSONObject legs1 = legs.getJSONObject(0);
      
                      JSONObject distance = legs1.getJSONObject("distance");
      
                      JSONObject duration = legs1.getJSONObject("duration");
      
                      distanceText = distance.getString("text");
      
                      durationText = duration.getString("text");
      
                  } catch (JSONException e) {
                      e.printStackTrace();
                  }
      
              }
          }
      

      【讨论】:

      • 请提供'data = downloadUrl(url[0]);'的代码
      猜你喜欢
      • 2016-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多