【问题标题】:How can I get travel time between two location on google map in android?如何在android的谷歌地图上获取两个位置之间的旅行时间?
【发布时间】:2019-02-25 14:31:48
【问题描述】:

我可以使用direction 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 的谷歌地图中使用方向 api 获取旅行时间?

【问题讨论】:

    标签: android google-maps


    【解决方案1】:

    我推荐谷歌的Distance Matrix 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 的任何例子吗?我可以试试,但我无法获得旅行时间
    【解决方案2】:

    您可以使用路线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];
    }
    

    调用此方法将返回距离。根据您的要求更改url中的查询参数。

    【讨论】:

    • get error E/e: org.json.JSONException: Index 0 out of range [0..0)
    • 在您的谷歌云平台和您的网址密钥中启用路线
    • 我更改了 url 并启用了方向 api,但它的错误索引 0 超出范围
    • 您是否将您的 api 密钥添加为 url 中的参数之一?像这样的东西 "maps.googleapis.com/maps/api/directions/json?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric&mode=driving&key=YOUR_KEY"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 2019-04-16
    • 2014-07-12
    • 1970-01-01
    • 1970-01-01
    • 2020-09-03
    相关资源
    最近更新 更多