Revoke the prior invocation of the Google Maps geocoding function

While working on implementing an autocomplete with JavaScript and the Google Maps geocode method (using the keyup event on input), I have encountered a problem where I sometimes receive the results of the previous search instead of the current one.

I am looking for a way to cancel the previous call if it has not finished yet. Can anyone provide assistance?

getAddressLatLng : function(text,callback) {
    var geocoder = new google.maps.Geocoder();
     geocoder.geocode({
         address : text,
         region : Utils.getRegion()
     },
     function(results, status) {
         if (status == google.maps.GeocoderStatus.OK) {
             callback(results);
         }
     });
},

Answer №1

To prevent multiple requests, consider implementing a global request counter that only triggers the callback if it remains unchanged. For example:

var requests = 0;
...
    getAddressLatLng : function(text,callback) {
        var requestNum;
        requests++;
        requestNum = requests;
        var geocoder = new google.maps.Geocoder();
         geocoder.geocode({
             address : text,
             region : Utils.getRegion()
         },
         function(results, status) {
             if(requestNum != requests) return;
             if (status == google.maps.GeocoderStatus.OK) {
                 callback(results);
             }
         });
    },

Additionally, I recommend incorporating debouncing or throttling in your function to avoid unnecessary requests and conserve bandwidth. You can use libraries like Underscore.js which provide convenient functions for this purpose.

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

Is it possible to use JavaScript for detecting third-party videos?

I'm currently developing an HTML5 video player that also has a fallback to flash. One of the challenges I am facing is that the video content is being provided by various third-party sources. It seems that some of these third parties serve videos bas ...

Having trouble with the Moment.js diff function in your React Native project?

Within my React Native application, I have implemented Moment.js and included the following code snippet: const expDate = moment(new Date(val)).format('MM-DD-YYYY'); const nowDate = moment().format('MM-DD-YYYY'); const diff = nowDate.d ...

The route path consists of data that will be retrieved before entering the route

I am facing an issue with my router configuration. I have a dynamic Route that requires the last part of its path to be set after fetching data from a store call in beforeRouteEnter. beforeRouteEnter (to, from, next) { if(to.params.categoryId) { next(vm ...

Having trouble with $(document).ready not functioning correctly?

After following the instructions to move my jQuery CDN to the bottom of the page, I encountered a problem. The script below was functioning perfectly when my jquery files were at the top of the page: if ($(window).width() >= 768) { $('.col-l ...

When executing a JavaScript program, an error with the message 'MODULE_NOT_FOUND' appeared, causing the internal module loader in Node to throw an error at line 1145

node:internal/modules/cjs/loader:1145 throw err; ^ Error: Module 'C:\Users\sande\3D Objects\JavaScript-Lesson\lesson08.js' not found at Module._resolveFilename (node:internal/modules/cjs/loader:1142:15) at Mo ...

When an Ajax call is made, my .html page transforms into a .php page using jQuery

The Issue While using my PHP function to send emails, everything goes smoothly. However, I'm facing an issue where I don't want the page to refresh, so I've implemented AJAX in the code below: reservation.html <form class="form-horizon ...

In the Rails environment, it is important to verify that the data sent through $.post method in jQuery is correctly

I’m facing an issue with my jQuery script when trying to post data as shown below: $.post({ $('div#location_select').data('cities-path'), { location_string: $('input#city_name').val() }, }); Although this code work ...

Ajax Syntax Error: Unexpected Token U

I have been struggling all day with an issue while trying to send json data via ajax to Express. Here is how my ajax code looks like: $('#saveClause').click(function () { var username = document.getElementById('postUserName').inne ...

Executing a Particular Function in PHP with Arguments

As a newcomer to PHP and JavaScript, I'm attempting to invoke a specific function in a PHP file from JavaScript. Here is my code: <script> function load($dID) { $.ajax({ url: "myPHP.php", ...

Saving compiled babel files to the corresponding directory level

Is there a way to output compiled babel files in the same directory as the source files? Currently, my script generates the compiled files in a separate folder while maintaining the folder structure. This is achieved through the following code snippet in m ...

What is the best way to connect or link to a HTML table row <tr>

Is there a way to trigger an alert when the user double clicks on the whole row? ...

Retrieve information from a JSON file according to the provided input

Can someone help me fetch data based on user input in JavaScript? When the input is 'Royal Python', I'm supposed to retrieve details about it. However, the code provided gives an error stating 'The file you asked for does not exist&apo ...

Dragging a stack of cards in a game of Solitaire using jQuery UI

I'm currently in the process of creating a Solitaire card game using Javascript. To enable dragging and dropping functionality for the cards, I am utilizing jQueryUI. In the example provided at http://jsfiddle.net/HY8g7/1/, you can see how the cards c ...

The precision of the css function in jQuery

Possible Duplicate: jQuery and setting margin using jQuery In the HTML snippet below, I have set margins for a paragraph element to center it: <p style="margin-left:auto; margin-right:auto; width:200px;">Hello</p> After that, I attempted ...

Emphasize a passage by clicking on a different section of text

Seeking Assistance I am currently customizing this template which incorporates the MixItUp plugin. My query pertains to highlighting the "filter tab" upon clicking on the corresponding text when hovering over each image, a task I find challenging as a new ...

Displaying the URL of a link on the screen using jQuery

I am looking for a solution to add a link address after the link itself in a table containing reference links for our staff. I have used CSS to achieve this in the past, but the address was not copyable by users. Instead, I am interested in using jQuery&ap ...

Is there a way for me to display information from a secondary child component by simply clicking a button on the main component instance?

Consider a scenario where there is a main instance, a child component named "movie-card," and another child component within "movie-card" called "link-btn." The objective is to create a selector that loops through the "link-btn" component using v-for. Addi ...

What is the best way to execute multiple Protractor test suites simultaneously?

Exploring Protractor for the first time. My goal is to run multiple test suites in a sequence. I have a complex angular form with various scenarios, each with its expected results. I want to execute all tests with just one command. Initially, I tried enter ...

regex execution and testing exhibiting inconsistent behavior

The regex I am using has some named groups and it seems to match perfectly fine when tested in isolation, but for some reason, it does not work as expected within my running application environment. Below is the regex code that works everywhere except in ...

Using D3-GraphViz in Javascript along with an Angular template: A step-by-step guide

I am attempting to integrate d3-graphviz following the guidance provided here within an angular template, like in this example. The tutorial on the d3-graphviz website advises me to include the following code in the index.html file: <!DOCTYPE html> & ...