Android - How to get estimated drive time from one place to another?

33,968

Solution 1

yes you get the time and distance value as well as many like direction details in driving, walking etc mode. all you got from the google direction api service

check our this links

http://code.google.com/apis/maps/documentation/directions/

Solution 2

    Location location1 = new Location("");
    location1.setLatitude(lat);
    location1.setLongitude(long);

    Location location2 = new Location("");
    location2.setLatitude(lat);
    location2.setLongitude(long);

    float distanceInMeters = location1.distanceTo(location2);

EDIT :

    //For example spead is 10 meters per minute.
    int speedIs10MetersPerMinute = 10;
    float estimatedDriveTimeInMinutes = distanceInMeters / speedIs10MetersPerMinute;

Please also see this, if above not works for you:

Calculate distance between two points in google maps V3

Solution 3

Deprecation note The following described solution is based on Google's Java Client for Google Maps Services which is not intended to be used in an Android App due to the potential for loss of API keys (as noted by PK Gupta in the comments). Hence, I would no longer recommened it to use for production purposes.


As already described by Praktik, you can use Google's directions API to estimate the time needed to get from one place to another taking directions and traffic into account. But you don't have to use the web API and build your own wrapper, instead use the Java implementation provided by Google itself, which is available through the Maven/gradle repository.

  1. Add the google-maps-services to your app's build.gradle:

    dependencies {
        compile 'com.google.maps:google-maps-services:0.2.5'
    }
    
  2. Perform the request and extract the duration:

    // - Put your api key (https://developers.google.com/maps/documentation/directions/get-api-key) here:
    private static final String API_KEY = "AZ.."
    
    /**
    Use Google's directions api to calculate the estimated time needed to
    drive from origin to destination by car.
    
    @param origin The address/coordinates of the origin (see {@link DirectionsApiRequest#origin(String)} for more information on how to format the input)
    @param destination The address/coordinates of the destination (see {@link DirectionsApiRequest#destination(String)} for more information on how to format the input)
    
    @return The estimated time needed to travel human-friendly formatted
    */
    public String getDurationForRoute(String origin, String destination)
        // - We need a context to access the API 
        GeoApiContext geoApiContext = new GeoApiContext.Builder()
            .apiKey(apiKey)
            .build();
    
        // - Perform the actual request
        DirectionsResult directionsResult = DirectionsApi.newRequest(geoApiContext)
                .mode(TravelMode.DRIVING)
                .origin(origin)
                .destination(destination)
                .await();
    
        // - Parse the result
        DirectionsRoute route = directionsResult.routes[0];
        DirectionsLeg leg = route.legs[0];
        Duration duration = leg.duration;
        return duration.humanReadable;
    }
    

For simplicity, this code does not handle exceptions, error cases (e.g. no route found -> routes.length == 0), nor does it bother with more than one route or leg. Origin and destination could also be set directly as LatLng instances (see DirectionsApiRequest#origin(LatLng) and DirectionsApiRequest#destination(LatLng).

Further reading: android.jlelse.eu - Google Maps Directions API

Solution 4

You can also use http://maps.google.com/maps?saddr={start_address}&daddr={destination_address}

it will give in direction detail along with distance and time in between two locations

http://maps.google.com/maps?saddr=79.7189,72.3414&daddr=66.45,74.6333&ie=UTF8&0&om=0&output=kml

Share:
33,968
ZeeShaN AbbAs
Author by

ZeeShaN AbbAs

Principal Software Engineer Tkxel, Lahore

Updated on February 05, 2020

Comments

  • ZeeShaN AbbAs
    ZeeShaN AbbAs about 4 years

    I need to find the estimate drive time from one place to another. I've got latitudes and longitudes for both places but I have no idea how to do that. Is there is any API for that. help thanks.

  • Nikunj Patel
    Nikunj Patel over 12 years
    i think this will return km not time
  • Yaqub Ahmad
    Yaqub Ahmad over 12 years
    This will return distance in meters & thats why i wrote "Now you have the distanceInMeters so you can calculate the estimated drive time."
  • Nikunj Patel
    Nikunj Patel over 12 years
    can you tell me how can i get time?
  • ZeeShaN AbbAs
    ZeeShaN AbbAs over 12 years
    I don't need the url for navigate between two places. I need the estimated travel time in local variable...
  • ZeeShaN AbbAs
    ZeeShaN AbbAs over 12 years
    thanks for ur reply. but that is for javascript I need for android phone application..
  • ZeeShaN AbbAs
    ZeeShaN AbbAs over 12 years
    thanks for your reply but I don't need the url for navigate between two places. I need the estimated travel time in local variable...
  • Pratik
    Pratik over 12 years
    you can use this service in android also just you need to call the service using http package
  • ZeeShaN AbbAs
    ZeeShaN AbbAs over 12 years
    I appreciate ur answer but I have got one problem is that I dont know the meeterPerMinutes time and this method doesn't provide the distance calculation road by road. So I think I have to use Google MAP API for that...
  • ZeeShaN AbbAs
    ZeeShaN AbbAs over 12 years
    I can't find estimated time there. can u provide any reference specific for time.
  • Pratik
    Pratik over 12 years
    try to execute this maps.googleapis.com/maps/api/directions/… in browser and save the json file in that you find the duration. From individual step duration as well as total duration travelling available in this
  • ban-geoengineering
    ban-geoengineering almost 9 years
    But doesn't the above code give you the straight-line distance rather than the driving distance?? I don't see how you can simply translate on to the other without mapping/road info.
  • Ryhan
    Ryhan over 7 years
    be aware the travel time given by this answer ignores the physical route itself and traffic time
  • Feathercrown
    Feathercrown about 7 years
    This doesn't take roads into account. For example, it would tell me I could drive from California to Hawaii.
  • PK Gupta
    PK Gupta about 5 years
    Use of this java API is discouraged for client side usage. "The Java Client for Google Maps Services is designed for use in server applications. This library is not intended for use inside of an Android app, due to the potential for loss of API keys." github.com/googlemaps/google-maps-services-java
  • Brian
    Brian almost 3 years
    It's my best solution with directionsResult.routes[0].legs[0].duration getting the shortest distance by road. You need to enable DirectionsApi in Google cloud though