簡體   English   中英

如何獲取Android上Google地圖上兩個位置之間的旅行時間?

[英]How can I get travel time between two location on google map in android?

我可以使用方向api和此方法獲取兩個位置之間的距離

我的代碼用於獲取距離:

 @Override
  public void onDirectionSuccess(Direction direction, String rawBody) {
    if (getActivity() != null) {
        if (direction.isOK()) {
            ArrayList<LatLng> directionPositionList = 
  direction.getRouteList().get(0).getLegList().get(0).getDirectionPoint();

 myMap.addPolyline(DirectionConverter.createPolyline(getActivity(), 
 directionPositionList, 5, Color.RED));
            myMap.addMarker(new MarkerOptions().position(new 
 LatLng(origin.latitude, origin.longitude)).title("Pickup 
 Location").snippet(pickup_address).
 icon(BitmapDescriptorFactory.defaultMarker
 (BitmapDescriptorFactory.HUE_RED)));
  myMap.addMarker(new MarkerOptions().position(new 
 LatLng(destination.latitude, destination.longitude))
.title("Drop Location").snippet(drop_address).icon
(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
            myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(origin, 
10));

  calculateDistance(Double.valueOf(direction.getRouteList()
 .get(0).getLegList().get(0).getDistance().getValue()) / 1000);

如何在Android的Google地圖中使用Directional API獲取旅行時間?

我推薦Google的距離矩陣API 使用此方法可以設置最准確的旅行時間的運輸方式。

try{
        val context = GeoApiContext.Builder()
                .apiKey(Constants.GOOGLE_API_KEY)
                .build()

        val req = DistanceMatrixApi.newRequest(context)
        val origin = LatLng(fromlocation.getLatitude(), fromlocation.getLongitude())
        val destination = LatLng(tolocation.getLatitude(), tolocation.getLongitude())

        val trix = req.origins(origin)
                .destinations(destination)
                .mode(TravelMode.DRIVING)
                .await()

        eta = trix.rows[0].elements[0].duration.humanReadable

    }catch (ex:Exception){
        Log.e("ETA", ex.message)
    }

您可以使用路線API查找起點和終點之間的距離

 public String getDistance(final double lat1, final double lon1, final double lat2, final double lon2) {
    final String[] parsedDistance = new String[1];
    final String[] response = new String[1];
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {

                URL url = new URL("https://maps.googleapis.com/maps/api/directions/json?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric&mode=driving");
                Log.v("urldirection", url.toString());
                final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                InputStream in = new BufferedInputStream(conn.getInputStream());
                response[0] = org.apache.commons.io.IOUtils.toString(in, "UTF-8");

                JSONObject jsonObject = new JSONObject(response[0]);
                JSONArray array = jsonObject.getJSONArray("routes");
                JSONObject routes = array.getJSONObject(0);
                JSONArray legs = routes.getJSONArray("legs");
                JSONObject steps = legs.getJSONObject(1);
                JSONObject distance = steps.getJSONObject("duration");
                parsedDistance[0] = distance.getString("text");

            } catch (JSONException | IOException e) {
                Log.v(TAG, e.toString());
            }
        }
    });
    thread.start();
    try {
        thread.join();
    } catch (InterruptedException e) {
        Log.v("DistanceGoogleAPi", "Interrupted!" + e);
        Thread.currentThread().interrupt();
    }
    return parsedDistance[0];
}

調用此方法將返回距離。根據您的要求更改網址中的查詢參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM