Get the distance between two locations in android?

前端 未结 10 553
醉梦人生
醉梦人生 2020-11-28 07:57

i need to get distance between two location, but i need to get distance like blue line in the picture. \"picure\"

10条回答
  •  抹茶落季
    2020-11-28 08:54

    public String getDistance(final double lat1, final double lon1, final double lat2, final double lon2){
        String parsedDistance;
        String response;
    
        Thread thread=new Thread(new Runnable() {
          @Override
          public void run() {
            try {
              URL url = new URL("http://maps.googleapis.com/maps/api/directions/json?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric&mode=driving");
              final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
              conn.setRequestMethod("POST");
              InputStream in = new BufferedInputStream(conn.getInputStream());
              response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
    
              JSONObject jsonObject = new JSONObject(response);
              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");
              parsedDistance=distance.getString("text");
            } catch (ProtocolException e) {
              e.printStackTrace();
            } catch (MalformedURLException e) {
              e.printStackTrace();
            } catch (IOException e) {
              e.printStackTrace();
            } catch (JSONException e) {
              e.printStackTrace();
            }
          }
        });
    
        thread.start();
    
        try {
          thread.join();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
    
        return parsedDistance;
    }
    

提交回复
热议问题