Search code examples
javascripthtmlgoogle-mapsgoogle-directory-apigoogle-distancematrix-api

Reading JSON data into a webpage/html form from Google Maps Distance API


I'm very new to Google Maps Distance API. I'm trying to create a form that calculates the distance between two points using long and lat.

<a href="https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=53.487362,-2.227197&destinations=51.516595,-0.129279&key=API_KEY">
click here for distance
</a>

Clicking the link gives me a results page in JSON format.

l

How I do read the "distance:text" (209 mi) data and put the value into a <div> or <input> on the same page.

Thanks in advance.


Solution

  • It looks like you need to get and display this data on the client-side, so you should use JavaScript to call the client-side Distance Matrix service. Not the web service (which is called server-side). E.g.:

    HTML

    <button id="distance-btn" onClick="getDistance()">
      Click here for distance
    </button>
    <div id="distance"></div>
    

    JS

    function getDistance() {
      const origin = '53.487362,-2.227197';
      const destination = '51.516595,-0.129279';
    
      var distanceService = new google.maps.DistanceMatrixService();
      distanceService.getDistanceMatrix({
        origins: [origin],
        destinations: [destination],
        travelMode: 'DRIVING',
        unitSystem: google.maps.UnitSystem.IMPERIAL,
        avoidHighways: false,
        avoidTolls: false
      }, function(response, status) {
        if (status !== 'OK') {
          alert('Error was: ' + status);
        } else {
          const distance = response.rows[0].elements[0].distance.text
          document.getElementById('distance').innerText = distance;
        }
      });
    }
    

    Working jsfiddle.

    Having said that, if you only want to compute the distance between 1 origin and 1 destination then you're better off using the Directions service instead. Check out this other fiddle.

    Hope this helps!