Using Javascript to query Google Distance Matrix API
<p>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.</p>

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

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

<p>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:</p>

<blockquote>
  <p>Uncaught SyntaxError: Unexpected token :</p>
</blockquote>

<p>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.</p>

<p>How can I make the request and then use the JSON response that is returned?</p>

<p>Here is the function that I am using to make the request at the moment:</p>

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

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

<pre><code>{
   "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"
}
</code></pre>