Within the code snippet below (keep an eye on the error console!), I am rapidly querying Google Maps for ten different locations to determine whether it can calculate a route to them or not. While this method does work, I require the result from Google to be received prior to proceeding with the loop (so that the status from Google appears in alternating lines in the console, instead of after my loop has completed as it does currently).
Is there a way to achieve this?
After experimenting with callbacks extensively without success, I stumbled upon a solution here: Google Maps V3 setDirections() callback, suggesting that I might need to utilize an event listener instead. Despite searching the API Reference, I came up empty-handed on any related information... but considering my relative newness to this, perhaps someone here could offer some insights?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title></title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?"></script>
</head>
<body style="font-family: Arial; font-size: 12px; color:#FFFFFF;" bgcolor="#202020">
<div id="map" style="width: 300px; height: 300px;"></div>
<script type="text/javascript">
var counter = 0;
var destination_lat = 52.498775;
var destination_long = 13.518474;
do {
var destination_long = (destination_long + 0.2);
var destination = destination_lat + ", " + destination_long;
var finaldestination = destination.toString();
calcRoute();
console.error('longitude: ' + destination_long.toFixed (1) + ', counter: ' + counter);
counter = (counter + 1);
}
while (counter < 10);
function calcRoute() {
var directionsService = new google.maps.DirectionsService();
var request = {
origin: 'Potsdamer Platz, 10785 Berlin',
destination: finaldestination,
travelMode: google.maps.DirectionsTravelMode.TRANSIT,
};
directionsService.route(request, function(response, status) {
console.error('DirectionsStatus is ' + status);
});
}
</script>
</body>
</html>