简体   繁体   English

如何获取Android上Google地图上两个位置之间的旅行时间?

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

I can get distance between two location using direction api and this method 我可以使用方向api和此方法获取两个位置之间的距离

My code is for get distance: 我的代码用于获取距离:

 @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);

How can I get travel time using direction api in google map in android ? 如何在Android的Google地图中使用Directional API获取旅行时间?

I recommend the Distance Matrix Api from google. 我推荐Google的距离矩阵API Using this method allows you to set the mode of transportation for the most accurate travel time. 使用此方法可以设置最准确的旅行时间的运输方式。

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

You can use directions api to find the distance between the origin and destination 您可以使用路线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];
}

calling this method will return the distance.Change the query parameters in the url as per your requirement. 调用此方法将返回距离。根据您的要求更改网址中的查询参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何获取谷歌地图中两个位置之间的总旅行时间? - How to get total travel time between two location in google map? Google Map Android API V2中两个位置之间的行驶距离和行驶时间 - Driving distance and travel time duration between two locations in Google Map Android API V2 Google Map Android API V2中两个位置之间的旅行时间 - travel time between two locations in Google Map Android API V2 如何使用带有标记的Android在Google Map中的两个位置之间绘制折线? - How can I draw polyline Between two location in Google Map using Android with marker? 如何使用Android在Google Map中的两个位置之间绘制折线? - How can I draw polyline Between two location in Google Map using Android? 使用android studio获取两点之间的旅行时间的问题 - Issues using android studio to get time of travel between two points 如何在Android应用程序中找到在两个地方之间旅行所需的时间 - How to find the time it will take to travel between two places in an android app 我如何找到我在两个地点之间旅行所需的距离和时间? - How can i find distance and time taken by me to travel between two locations? Android-如何在Google Map中实现位置准确性 - Android - how I can I achieve location accuracy in Google Map 如何在Android中使用Google Map API获取最近的位置? - How can i get the nearest location by using google map api in android?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM