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