Using Google Maps API to get travel time data

Viewed 110677

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?

6 Answers

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.

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