Like what the title says the bottom code is being read even if the loop at top isn't done yet.

When you i look into the console the "rows" in distance[$x].rows[0].elements[0].distance.text isn't define yet because the push method isn't in effect yet.

btw this event is called after an event click so the first click there won't be anything on the array but on the second click there it'll work just as i wanted.

i've already tried using the promise and await but still the same.

var distanceService = new google.maps.DistanceMatrixService;

for($z=0;$z<ppos.length;$z++){
  distanceService.getDistanceMatrix({
      origins: [pos],
      destinations: [ppos[$z]],
      travelMode: 'DRIVING',
    },
    function (response, status) {
      if (status != google.maps.DistanceMatrixStatus.OK) {
        console.log('Error:', status);
      } else {
        console.log(response);
        distance.push(response);
      }
    }
  );
}

var content="";

if(distance.length>0){
  for($x=0;$x<3;$x++){
    content+='<div class="row"><div class="col-lg-12"><h4><strong>'+plists[$x].name+'</strong></h4><p><em>Address:'+plists[$x].vicinity+'</em></p><p><em>Distance:'+distance[$x].rows[0].elements[0].distance.text+'</em></p></div></div>';
  }
}

what i wanted is the values should be putted into the distance array first before reading the bottom codes.

1 Answers

0
Mosè Raguzzini On

Check for the last loop before getting distances, async calls are called in for loops but the loop does not wait for their responses:

var res = 0;
var distanceService = new google.maps.DistanceMatrixService();
    for ($z = 0; $z < ppos.length; $z++) {
        distanceService.getDistanceMatrix(
            {
                origins: [pos],
                destinations: [ppos[$z]],
                travelMode: "DRIVING"
            },
            function(response, status) {
                // Response has arrived!
                res ++;
                if (status != google.maps.DistanceMatrixStatus.OK) {
                    console.log("Error:", status);
                } else {
                    console.log(response);
                    distance.push(response);
                    // If it is the last loop...
                    if(res === ppos.length) {
                       getDistance();
                    }
                }
            }
        );
    }

    var content = "";

    function getDistance() {
        if (distance.length > 0) {
            for ($x = 0; $x < 3; $x++) {
                content +=
                    '<div class="row"><div class="col-lg-12"><h4><strong>' +
                    plists[$x].name +
                    "</strong></h4><p><em>Address:" +
                    plists[$x].vicinity +
                    "</em></p><p><em>Distance:" +
                    distance[$x].rows[0].elements[0].distance.text +
                    "</em></p></div></div>";
            }
        }
    }