41

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?

M--
  • 25,431
  • 8
  • 61
  • 93
Felix Andersen
  • 1,381
  • 2
  • 14
  • 26

6 Answers6

27

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.

M--
  • 25,431
  • 8
  • 61
  • 93
Barry
  • 279
  • 3
  • 2
  • 6
    A link to these findings would be very beneficial to all readers. – Boeckm Nov 08 '12 at 12:58
  • 3
    It 10.1 (g) under License Restrictions: https://developers.google.com/maps/terms – hurrymaplelad Jan 08 '13 at 07:51
  • 3
    Which would be then the correct way to do it? – Alvaro May 10 '13 at 09:43
  • 1
    Display a map, or use MapQuest Directions API – M H Apr 06 '15 at 21:05
  • 4
    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. – Jean-François Beauchamp Mar 10 '16 at 21:47
  • 1
    is this allowed with a static google map image? – Loser Coder May 05 '16 at 23:20
  • 9
    I guess It changed: "You can display Distance Matrix API results on a Google Map, or without a map.", source: https://developers.google.com/maps/documentation/distance-matrix/policies – user1762087 May 12 '19 at 07:17
  • @user1762087 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. – Antoine Aug 22 '19 at 08:20
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.

BioGeek
  • 21,897
  • 23
  • 83
  • 145
RedBlueThing
  • 42,006
  • 17
  • 96
  • 122
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 + ')' );
    }
} );
Igor Parra
  • 10,214
  • 10
  • 69
  • 101
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
Saurabh Chandra Patel
  • 12,712
  • 6
  • 88
  • 78
  • 1
    This appears to yield the driving time under ideal traffic conditions (ignoring current conditions). The results are identical regardless of departure time. – Ken Seehart Jun 11 '16 at 00:57
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.

andrewtweber
  • 24,520
  • 22
  • 88
  • 110
  • 2
    I guess It changed: "You can display Distance Matrix API results on a Google Map, or without a map.", source: https://developers.google.com/maps/documentation/distance-matrix/policies – user1762087 May 12 '19 at 07:16
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);
  });
M--
  • 25,431
  • 8
  • 61
  • 93