javascriptgoogle-distancematrix-api

Google Distance Matrix - parse response and insert in html element - javascript


Scenario:

  1. I get a list of business places from DB and it looks like this
<div class="list-items"> 
.... 
<div id="distance" data-distance="<?= $placeid; ?>"></div>
</div>
  1. Then i play with "geolocation.getCurrentPosition" and put all markers to a Map
  2. Once i have "origin" coordinates and all Places coordinates i'm going to calculate the Distance and Travel Time. At the moment i'm arrived at this point:
...
const destinations = [];
// initialize services distance matrix
const service = new google.maps.DistanceMatrixService();
const origin = { lat: +lat, lng: +lng};

   for (var k in results_obj) {
       var place = results_obj[k];
       /* 
       output of "place" object
       ...
       lat: "41.87028400"
       lng: "12.45226500"
       ...
       place_id: 4677
       ...
       */
       
        /* there i get an array  of places coordinates and then pass to request*/
        destinations.push(new google.maps.LatLng(p.lat, p.lng));
      
       ...
       }

       // build request
        const request = {
          origins: [origin],
          destinations: destinations,
          travelMode: google.maps.TravelMode.DRIVING,
          unitSystem: google.maps.UnitSystem.METRIC,
          avoidHighways: true,
          avoidTolls: false,
        };

      // get distance matrix response
        
     service.getDistanceMatrix(request).then((response) => {
      // put response
     //document.getElementById("distance").innerText = JSON.stringify(response, null, 2);
                   
      console.log(response.rows[0]);

   });  
...

The console.log(response.rows[0].elements[0]); output it's llooks like this

    .   {elements: Array(3)}
    .   elements: Array(3)
    .   0:
    .   distance: {text: '1,0 km', value: 961}
duration: {text: '4 min', value: 215}
status: "OK"

    .   1:
    .   distance: {text: '1,9 km', value: 1876}
duration: {text: '7 min', value: 398}
status: "OK"

    .   2:
    .   distance: {text: '1,5 km', value: 1547}
duration: {text: '5 min', value: 277}
status: "OK"





Till now it's seems to work all fine. I need your help to put "distance" and "duration" values to the html element

so this code

<div class="list-items"> 
.... 
<div id="distance" data-distance="<?= $placeid; ?>"></div>
</div>

have to become something like this

<div class="list-items"> 
.... 
<div id="distance" data-distance="<?= $placeid; ?>">
<span>Distance: 1km</span> - <span> Duration: 5 min</span>
</div>
</div>

Update

// get distance matrix response
                service.getDistanceMatrix(request).then((response) => {
                    // put response
                    var results = response.rows[0].elements;

                    for (var j = 0; j < results.length; j++){
                        distance = results[j].distance.text;
                        duration = results[j].duration.text;
                        console.log(distance);
                        console.log(duration);

                    }
                });

now i can extract distance and duration for each location.

Note: $placeid; is an integer value of business place.

Thank you.


Solution

  • This is the sollution

    service.getDistanceMatrix(request).then((response) => {
                var results = response.rows[0].elements;
                var distancesDOM = document.getElementsByClassName('distance');
                for (var j = 0; j < results.length; j++){
                    var distance = results[j].distance.text;
                    var duration = results[j].duration.text;
                    var htmlContent = `<span><img src="//maps.gstatic.com/tactile/pane/travel-modes/2x/walk_black.png" style="opacity: .6; top: 16px; width: 22px; height: 22px;">${distance} - ${duration}</span>`;
                    distancesDOM[j].innerHTML = htmlContent;
                }
            });