Using Javascript to query Google Distance Matrix API

James picture James · Jul 2, 2016 · Viewed 10.9k times · Source

I'm not very fluent with Javascript, but am trying to build a simple web app using it to try and learn a bit more.

I'm wanting to use the Google Distance Matrix API to let me query the distance between two addresses.

I have two input fields that use the autocomplete function of Google to get the address and then I use the place_id of the addresses to make a query to the API.

I believe I need to use JSONP to make the call to the API and get the data, but I'm having trouble using the response and I get the following error in my console:

Uncaught SyntaxError: Unexpected token :

I've been searching around and everyone is using PHP in conjunction with JSONP - however I'm wanting to avoid this and keep the whole process client-side.

How can I make the request and then use the JSON response that is returned?

Here is the function that I am using to make the request at the moment:

function getDistance()
    {
      //Find the distance
      $.getJSON("https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=place_id:" + $("#autocompleteDeparture").data("place_id") + "&destinations=place_id:" + $("#autocompleteArrival").data("place_id") + "&key=MY_API_KEY0&callback=?", function(data) {
          data = JSON.parse(data);
          console.log(data);
      });
    }

If I check the request, it is running successfully and returning the correct JSON data:

{
   "destination_addresses" : [ "9 Coach Ln, Belmont, Lower Hutt 5010, New Zealand" ],
   "origin_addresses" : [ "3/30 Rata St, Naenae, Lower Hutt 5011, New Zealand" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "4.9 km",
                  "value" : 4934
               },
               "duration" : {
                  "text" : "8 mins",
                  "value" : 509
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

Answer

James picture James · Jul 3, 2016

After some more digging I found that the API does not support JSONP and that I could use the distance matrix service directly through JavaScript like so:

function getDistance()
  {
     //Find the distance
     var distanceService = new google.maps.DistanceMatrixService();
     distanceService.getDistanceMatrix({
        origins: [$("#autocompleteDeparture").val()],
        destinations: [$("#autocompleteArrival").val()],
        travelMode: google.maps.TravelMode.WALKING,
        unitSystem: google.maps.UnitSystem.METRIC,
        durationInTraffic: true,
        avoidHighways: false,
        avoidTolls: false
    },
    function (response, status) {
        if (status !== google.maps.DistanceMatrixStatus.OK) {
            console.log('Error:', status);
        } else {
            console.log(response);
            $("#distance").text(response.rows[0].elements[0].distance.text).show();
            $("#duration").text(response.rows[0].elements[0].duration.text).show();
        }
    });
  }