How can you tell when directionsService has finished processing and returned its status?

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>

Answer №1

After some thought, I realized that I didn't actually need an event listener as geocodezip mentioned in their comment - I still don't fully grasp the concept of asynchronity.

Despite my uncertainty, the code below achieves the desired outcome. I'm not sure if this is the most efficient way to do it, but it works (with a small adjustment to only make queries until a route is found):

<!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">
  <script type="text/javascript">


  var destination_lat = 53.5219216;
  var destination_long = 13.4110207;
  var finaldestination = 'lalala';
  var valid_route = 1; // reset to 0 once a route is found


  mainLoop();

  function mainLoop() {
    if (valid_route >= 1) {
      destination_long = (destination_long + 0.2);
      finaldestination = (destination_lat + ", " + destination_long);
      finaldestination = finaldestination.toString();
      calcRoute();
      console.error('longitude: ' + destination_long.toFixed(1) + ', loop count (valid_route): ' + valid_route);
    }
  }

  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) {
      if (status == google.maps.DirectionsStatus.OK) {
        valid_route = 0;
      }
      else {
        valid_route = (valid_route + 1);
      }
      console.error('DirectionsStatus is ' + status);
      mainLoop();
    });
  }


  </script>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for creating JSON using AngularJs to store tabular information

I successfully created an HTML page using AngularJS. <form name="target" ng-submit="createAllKeywordsJSON(codeMasterList)"><!-- createAllKeywordsJSON() --> <input type="submit" value="Save" class="myButton" name="submit" style="margin: ...

What is the method for activating a hook after a state change in a functional component?

I'm currently working on a custom pagination hook that interacts with an API to fetch data similar to React Query. The concept is straightforward. I aim to invoke this hook whenever a specific state (referred to as cursor) undergoes a change. Below i ...

Using Vue: Save user information in the Vuex store prior to registration

Hello fellow members of the Stackoverflow Community, I am currently working on a Vue.js application that involves user registration. The registration process is divided into three components: Register 1 (email, password), Register 2 (personal information) ...

Attempting to use Model.remove() is proving to be completely ineffective

Currently, I am utilizing expressjs (version 3.10.10), mongoose (version 3.10.10), and mLab for my project. Below is the code snippet: app.get("/deleteDevice/:query", function(req, res) { var query = req.params.query; query = JSON.stringify(quer ...

Tips for displaying a jQuery error message when a key is pressed

I am working with a textarea that has a word count limit of 500. I need to display an error message below the textarea if the word count exceeds 500. I have successfully calculated the word count, but I am unsure how to display the error message and preve ...

Utilizing JQuery to merge variable identifiers

Imagine a scenario where the variables are structured this way: localStorage.var1a = 0; localStorage.varnum = 1000; Now, consider the following code snippet: for(x = 1; x < localStorage.varnum; x++){ if(localStorage.var.x.a > 0){ localStora ...

What is the best way to enclose a bootstrap row within a clickable link generated by the twitch.tv API?

Recently, I completed a JSON/JavaScript project for Free Code Camp that retrieves streamer information like their logo, current status, and display name. My goal is to enclose entire Bootstrap 3 rows in hyperlinks linked to the streamers' pages, elim ...

Remove and modify an li element that has been dynamically generated within a ul list

Currently, I am facing an issue in my code. I am dynamically creating li elements by taking input from an input box and then appending the data within li tags using jQuery. However, after adding the li element, I have included a delete button. The problem ...

Angular JS is patient when waiting for asynchronous requests to complete

Once upon a time in a factory httpFactory.factory('setFavorability', function($http){ return{ Like: function(id){ return $http.get('http://localhost:51265/Film/Like/' + id); } } ...

Limit access to the server in Node.js by allowing loading only if the request is coming from another page and form POST variables are present

After searching for documentation without success, I have a question: Is there a way to prevent users from directly accessing my node.js server at website.com:3000? Currently, when a user visits my node.js website, it crashes the whole server and takes i ...

Incorporating Keyboard Features into Buttons

How can I toggle the page selectors in #pageList using a keyboard shortcut instead of clicking on the .togglePL button? I've tried looking up solutions online and asking questions here, but haven't found a working solution yet. Below is the code ...

The dropCollection function is failing to delete the collection

Version numbers: mongoose 4.0.3, node 0.10.22, mongod db version 3.0.1 I've been attempting to drop a collection using Mongoose, but I'm encountering issues. execute: function() { return Q(mongoose.connect('mongodb://127.0.0.1:27017/te ...

Ways to unmark the "select all" checkbox when any one of its children is no longer selected

Is there a way to automatically uncheck the "Select All" checkbox when any of its child checkboxes are deselected? In the code snippet provided, the goal is for the "Select All" checkbox to be unchecked if not all child checkboxes are selected. The script ...

Transfer a variable from javascript/jquery to a PHP script within the same page

Possible Duplicate: How to transfer JavaScript variables to PHP without using a form? What is the best way to move a JavaScript variable to a PHP script without the need for form submission? Is this even achievable? Ajax seems to be a viable solutio ...

Invoke a JavaScript file within the MongoDB shell

Running a JS file directly from the Mongo shell using the query mongo localhost:27017/west createSumCollection.js has resulted in an error: "uncaught exception: SyntaxError: unexpected token: identifier : @(shell):1:6" The content of CreateSu ...

Is there a simple method to submit to a URL without relying on ajax?

When it comes to using jQuery, the $.ajax() function is typically used for POST requests to a URL. However, in my particular situation, I am unable to use this function. I need the client to send a POST request to a URL and have the server redirect the use ...

Tips for gathering all links from a JSON object

When dealing with a JSON object of any structure, simple or complex, what would be the most efficient way to extract all URLs from the data and store them in an array for iteration in JavaScript? { "url": "https://example.com:443/-/m ...

The ancient oracle of Delphi and the modern login portal of Microsoft

I need to login to a site that utilizes . To streamline the process for end-users, I want to store credentials in an .ini file and inject them into a two-stage JavaScript online prompt. Is there a way to have Delphi run a program with a browser that auto ...

When utilizing the dojox.grid.enhanceGrid function to delete a row, the deletion will be reflected on the server side but

I have a grid called unitsGrid that is functioning correctly. I am able to add and delete rows, but the issue arises when I try to delete rows - they do not disappear from my unitsGrid. I have spent hours trying to debug the code but I cannot seem to fin ...

Retrieve information from a database by utilizing AJAX and store it in a JavaScript array

I'm facing an issue where I can retrieve data from the PHP file, but not from the database to my JavaScript code. I am using Ajax to fetch the data from the database, then passing it to the PHP file, and finally trying to filter this data using JavaSc ...