I'm trying to calculate the shortest distance of coordinates taken from a database using Google Map API to a given address. The problem is not there, I managed to alert a shorter distance whenever one is found.But the div named 'duration' has its innerHTML set to the initial value..
I don't get it, I know how scope works.. I've been coding for hours, maybe I just can't see clear anymore.
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var shortestDistance= 99999999;
var myOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var positions = new Array();
<?php
while($row = mysqli_fetch_array($result)){
echo'positions.push(['.$row['latitude'].','.$row['longitude'].']);';
}
?>
for(var i=0;i<positions.length;i++){
var originTemp = "";
originTemp += positions[i][0] + "," + positions[i][1];
var request = {
origin: originTemp,
destination: "1 Ste-Catherine St.",
durationInTraffic: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var newRoute = response.routes[0].legs[0].duration.value;
directionsDisplay.setDirections(response);
if(newRoute<shortestDistance){
shortestDistance=newRoute;
alert("New shorter distance: "+shortestDistance);
}
}
});
}
document.getElementById('duration').innerHTML += shortestDistance + " seconds";
</script>