Using Google Maps API to get travel time data [closed]
Asked Answered
K

6

42

All the examples I've come across using Google Maps API seem to show a map of some kind. I would like to incorporate the data about the estimated travel time by car they give you when you ask for a road description from A to B into a site. And only that data. Is it possible without loading up a map for the end visitor?

Kiker answered 25/6, 2009 at 9:30 Comment(0)
I
25

Yep, this is definitely possible using the API. You can construct a GDirections object without a map or directions div. You can do a load request from A to B and then call the getDuration method to get the total travel time.

First you need to create a directions object:

// no need to pass map or results div since
// we are only interested in travel time.
var directions = new GDirections (); 

Then do your load request to resolve the directions (I have used two latitudes and longitudes as my start and end points, but you can use addresses here as well):

var wp = new Array ();
wp[0] = new GLatLng(32.742149,119.337218);
wp[1] = new GLatLng(32.735347,119.328485);
directions.loadFromWaypoints(wp);

Then you need to listen for the load event so you can call getDuration once the directions have been resolved:

GEvent.addListener(directions, "load", function() {
    $('log').innerHTML = directions.getDuration ().seconds + " seconds";
        });

You can find the whole example here and the JavaScript here. You can check the Google Maps Documentation for more info about the options you can give the GDirections object (like walking distance etc...). You should also listen to the error event for geocoding failures.

Immediate answered 25/6, 2009 at 12:43 Comment(4)
now let's say I have a kml file with 50 points in it. I'd like to get the travel times between all these point, what do you recommend I should do?Aretta
The link does not work anymore!Deliberate
This appears to yield the driving time under ideal traffic conditions (ignoring current conditions). The results are identical regardless of departure time.Decedent
the whole example is dead - perhaps changes in the api?Kropotkin
I
26

The above answer is in violation of Google API terms of service, and hence, incorrect.

The Google Maps API only allows you to calculate travel time if it's referenced against a Google Map displayed to the user.

You can't use the API if you don't display a Google Map to the end user of the service.

Update:

Any answer here, that does not show the final results mapped on a google map, is in violation of the aforementioned terms of service and eventually, incorrect.

Ineluctable answered 8/11, 2012 at 12:37 Comment(8)
A link to these findings would be very beneficial to all readers.Edentate
It 10.1 (g) under License Restrictions: developers.google.com/maps/termsIndividualist
Which would be then the correct way to do it?Reminiscence
Display a map, or use MapQuest Directions APIGooseberry
With a commercial license, it is possible to get and display the travel time data without displaying a Google Map. Such an agreement has to be dealt with Google though. A client of the company I am working for is doing it. Since I am developing the solution, I asked them to forward me the confirmation of their Google sales representative stating so.Filigreed
is this allowed with a static google map image?Cornet
I guess It changed: "You can display Distance Matrix API results on a Google Map, or without a map.", source: developers.google.com/maps/documentation/distance-matrix/…Crafty
@Crafty yes, I was going to comment that. But still good to know it has changed because with the new API you have to be a paying customer. The original answer relates to the then free API that didn't allow that.Czechoslovakia
I
25

Yep, this is definitely possible using the API. You can construct a GDirections object without a map or directions div. You can do a load request from A to B and then call the getDuration method to get the total travel time.

First you need to create a directions object:

// no need to pass map or results div since
// we are only interested in travel time.
var directions = new GDirections (); 

Then do your load request to resolve the directions (I have used two latitudes and longitudes as my start and end points, but you can use addresses here as well):

var wp = new Array ();
wp[0] = new GLatLng(32.742149,119.337218);
wp[1] = new GLatLng(32.735347,119.328485);
directions.loadFromWaypoints(wp);

Then you need to listen for the load event so you can call getDuration once the directions have been resolved:

GEvent.addListener(directions, "load", function() {
    $('log').innerHTML = directions.getDuration ().seconds + " seconds";
        });

You can find the whole example here and the JavaScript here. You can check the Google Maps Documentation for more info about the options you can give the GDirections object (like walking distance etc...). You should also listen to the error event for geocoding failures.

Immediate answered 25/6, 2009 at 12:43 Comment(4)
now let's say I have a kml file with 50 points in it. I'd like to get the travel times between all these point, what do you recommend I should do?Aretta
The link does not work anymore!Deliberate
This appears to yield the driving time under ideal traffic conditions (ignoring current conditions). The results are identical regardless of departure time.Decedent
the whole example is dead - perhaps changes in the api?Kropotkin
C
22

For the record: At this time (year 2015) GDirections, GLatLng, GEvent, etc. are deprecated.


You can use google.maps.DirectionsService class (Google Maps JavaScript API V3)

In the following snippet, location and target are objects containing latitude and longitude coordinates.

1) The google.maps.DirectionsService class admit both LatLng and string values to feed their origin and destination properties.
2) A LatLng is a point in geographical coordinates: latitude and longitude.

var origin = new google.maps.LatLng( location.latitude, location.longitude ); // using google.maps.LatLng class
var destination = target.latitude + ', ' + target.longitude; // using string

var directionsService = new google.maps.DirectionsService();
var request = {
    origin: origin, // LatLng|string
    destination: destination, // LatLng|string
    travelMode: google.maps.DirectionsTravelMode.DRIVING
};

directionsService.route( request, function( response, status ) {

    if ( status === 'OK' ) {
        var point = response.routes[ 0 ].legs[ 0 ];
        $( '#travel_data' ).html( 'Estimated travel time: ' + point.duration.text + ' (' + point.distance.text + ')' );
    }
} );
Clothing answered 18/4, 2015 at 3:48 Comment(0)
I
6

from google.maps.DirectionsRenderer

Distance by using:

directionsDisplay.directions.routes[0].legs[0].distance.text

Duration by using:

directionsDisplay.directions.routes[0].legs[0].duration.text
Isotonic answered 19/3, 2016 at 11:16 Comment(1)
This appears to yield the driving time under ideal traffic conditions (ignoring current conditions). The results are identical regardless of departure time.Decedent
W
6
  1. First go here: https://developers.google.com/maps/documentation/distance-matrix/start You need to: Create or select a project, Enable the API and Get an API key Just click on the "Get a Key" and assuming you have a Gmail account you can get everything going (alternatively go to console.developer.google.com after logging in to your gmail account, and create an app, and enable the API, and get the API key there).
  2. Now go to https://developers.google.com/maps/documentation/distance-matrix/intro and follow the details. A couple things to note: use these: &mode=driving&departure_time=now&traffic_model=pessimistic if you want current traffic to influence your drive time. I also used &units=imperial

The duration in traffic is returned only if all of the following are true:

The request includes a departure_time parameter. The request includes a valid API key, or a valid Google Maps APIs Premium Plan client ID and signature. Traffic conditions are available for the requested route. The mode parameter is set to driving.

As of at least May 2019, you are now allowed display the drive time with or without a map.

You can display Distance Matrix API results on a Google Map, or without a map. If you want to display Distance Matrix API results on a map, then these results must be displayed on a Google Map. It is prohibited to use Distance Matrix API data on a map that is not a Google map.

Source: Distance Matrix usage limits, also checkout Google Maps Terms & Conditions

Note that Mapquest doesn't show drive times based on actual traffic.

Wilda answered 2/5, 2017 at 21:47 Comment(1)
I guess It changed: "You can display Distance Matrix API results on a Google Map, or without a map.", source: developers.google.com/maps/documentation/distance-matrix/…Crafty
B
2

I struggled with this for a long time but finally solved it with an AJAX call (make sure you're linked to jQuery to do this).

 //Pass parameters to a function so your user can choose their travel 
 locations

 function getCommuteTime(departLocation, arriveLocation) {
   //Put your API call here with the parameters passed into it
   var queryURL = 
   "https://maps.googleapis.com/maps/api/distancematrix/json?
   units=imperial&origins=" + departLocation + "&destinations=" + 
   arriveLocation + "&key=YOUR_API_KEY"

  //Ajax retrieves data from the API
  $.ajax({
  url: queryURL,
  method: "GET"
  }).then(function(response) {

    //Navigate through the given object to the data you want (in this 
     case, commute time)
    var commuteTime = response.rows[0].elements[0].duration.text;

    console.log(commuteTime)
   });

  } 


//This is where your user can give you the data you need
$("#addRoute").on("click", function(event) {

event.preventDefault();

var departLocation = $("#departInput").val().trim();
var arriveLocation = $("#arriveInput").val().trim();

//call the above function
getCommuteTime(departLocation, arriveLocation);
  });
Bash answered 7/2, 2018 at 20:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.