简体   繁体   中英

Using Javascript to query Google Distance Matrix API

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"
}

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();
        }
    });
  }
  1. Get your api key from https://console.developers.google.com/
  2. Get the latitude and longitude of the places that your wish to find the distance between. Convert them into LatLng objects.
  3. Use computeDistanceBetween function.

......

<script src="https://maps.googleapis.com/maps/api/js?key=<API-KEY>&libraries=geometry&language=en&callback=initMap" async defer></script>

<script type="text/javascript">
    function initMap(){
        srcLocation = new google.maps.LatLng(19.075984, 72.877656);
        dstLocation = new google.maps.LatLng(12.971599, 77.594563);
        var distance = google.maps.geometry.spherical.computeDistanceBetween(srcLocation, dstLocation)
        console.log(distance/1000); // Distance in Kms.
    }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM