Value replaced by ajax response

Currently experimenting with Google Maps and the Geocoder, my goal is to iterate through a list of addresses, retrieve LatLng coordinates for each one, and then use that data to create markers using the setMarker function provided below.

The issue I'm encountering is that the value of response[a] keeps getting overwritten by the last address in the list due to the for loop outpacing the AJAX responses. How can I preserve the correct data associated with the current response[a] during the iteration, so that it's available when setMarker() is eventually called?

Any insights or suggestions would be greatly appreciated. Thank you!

          var limit = 0;

          for (a in response){

            if(limit<5){ // limiting API calls

                  var addr = [response[a].Addr1, response[a].City, response[a].Zip];

                  geo = new google.maps.Geocoder();
                  geo.geocode({
                    address: addr.join(", "),
                    componentRestrictions: {
                    //  country: 'UK'
                    }
                  }, function (results, status) {

                    if (status == google.maps.GeocoderStatus.OK && results) {

                        var latitude = results[0].geometry.location.lat();
                        var longitude = results[0].geometry.location.lng();
                        var latlng = new google.maps.LatLng(latitude, longitude);

                        if(latitude!="" && longitude!=""){

                            bounds.extend(latlng);
                            map.fitBounds(bounds);
                            _this.setMarker(map, limit, latlng, response[a]);

                        }

                    } // if geo results

              });

            }

            limit++;

          }

Answer №1

The issue you are encountering is a common one that can be resolved by utilizing closure functions.

Your current code appears something like this:

var a[20];

for(i=0;i<20;i++) {
    some_async_method() {
        //code that utilizes 'a[i]'
    }
}

Implementing closure to maintain the scope of variable a within an async function:

var a[20];

for(i=0;i<20;i++) {
    (function(_a){
        some_async_method() {
            //code that uses 'a[i]' as '_a'
        }   
    })(a[i]); // self-invoking function that preserves the scope of a[i]
}

Therefore, your updated code will appear as follows:

var limit = 0;

for (a in response){

if(limit<5){ // limit API calls

      var addr = [response[a].Addr1, response[a].City, response[a].Zip];

      geo = new google.maps.Geocoder();
      (function(response_a){ // closure function to preserve scope of 'response[a]' 
          geo.geocode({
            address: addr.join(", "),
            componentRestrictions: {
            //  country: 'UK'
            }
          }, function (results, status) {

            if (status == google.maps.GeocoderStatus.OK && results) {

                var latitude = results[0].geometry.location.lat();
                var longitude = results[0].geometry.location.lng();
                var latlng = new google.maps.LatLng(latitude, longitude);

                if(latitude!="" && longitude!=""){

                    bounds.extend(latlng);
                    map.fitBounds(bounds);
                    _this.setMarker(map, limit, latlng, response_a);

                }

            } // if geo results

      });
    })(response[a]);

}

limit++;

}

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

In the realm of JavaScript, "this" is a key player when referring to an object within a factory

I created some JavaScript classes and FunctionFactories for them, but I believe there are errors in my implementation. To make the code more understandable, I decided to rename certain parts of it. The main class is called the "root"-class, which has chi ...

What is the appropriate import to use when working with FontAwesomeIcon, React, and Jest?

Currently, I am working on a React website built with TypeScript and Webpack. I am using FortAwesome's react-fontawesome package to display icons. The import statement for this package is as follows: import FontAwesomeIcon from '@fortawesome/rea ...

A guide to retrieving the contents of an input field based on its assigned value and name attributes through Javascript

Can anyone help me with selecting an input element in my HTML code? Here is the input I want to select: <input id="tb-radio-gym_custom_radio-10ce67e3" type="radio" value="OUI" name="form_fields[gym_custom_radio]" data-price-inc="0" checked="checked"> ...

What is the best way to showcase two SVG clocks on a single webpage?

The issue arises when combining the desktop and mobile versions of the clock script. The first clock works fine on its own, but upon duplicating another set of scripts for the second clock, it encounters display problems. I have appropriately labeled the c ...

Unable to view new content as window does not scroll when content fills it up

As I work on developing a roulette system program (more to deter me from betting than to actually bet!), I've encountered an issue with the main window '#results' not scrolling when filled with results. The scroll should always follow the la ...

Adding a class to radio buttons and checkboxes in Angular when they are checked or selected without needing to trigger a change event

I am looking to implement ngClass based on whether an item is checked or not. Essentially, I want the user to visually see which items are selected through radio buttons or check-boxes by adding a class to them, allowing me to apply different CSS styles to ...

Angular displays error ERR_UNKNOWN_URL_SCHEME when attempting to retrieve an image saved in a blob

As I transition my app from Electron to Angular, one of my main objectives is to display an image uploaded by a user. Here's how I attempted to achieve this: page.component.ts uploadImageFile(){ fileDialog({}, files =>{ //Utilizing the fileDi ...

Submitting a form without refreshing the page, displaying the output, reloading the form, and repeating the process. Wash,

There is a form on my page with dynamic drop-down options, an input box, and a submit button. To include this form on my page, I use the following code: <div id="dropdown"> <?php include("./listforward.php"); ?> </div> The listfo ...

Implementing multiple filters with jQuery

Make a Selection `<select class="form-control" id="technology"> <option name="sort" value="2g" id="2g"gt;2G</option> <option name="sort" value="3g" id="3g"&g ...

The issue arises when attempting to use input alongside debounce, event.persist(), and storing the value at the parent component

Is there a way to implement an input field with debounced search where the value is passed from the parent component? Currently, when I pass the value from the parent component it doesn't work as expected. What would be the correct approach to make th ...

Parsing error: Unforeseen token encountered. Consider adding a supplementary loader to manage the output of these loaders

Could someone please break down this syntax message?.length === 1 and show me how to convert it into standard JavaScript? https://i.stack.imgur.com/20Ui6.png I am encountering an error when trying to use a Vue.js component that I downloaded from another ...

Display information in a paginated format using components

As a newcomer to React, I may use the wrong terms so please bear with me. I am attempting to implement pagination for an array of components. To achieve this, I have divided the array into pages based on the desired number of items per page and stored eac ...

Value auto-populated from associated model

Currently, I have a situation where I have a table for zip codes and another table for persons. The goal is to automatically populate the city field in the person's table based on the zip code entered. It seems like this functionality may not be achie ...

Guide on transferring a JWT token to a Node.js backend

Recently, I developed a node.js server featuring a login system and am focused on safeguarding my routes. Despite creating middleware to authenticate each protected route, I keep encountering an "Authentication failed" message after logging in. How can I e ...

Retrieving, storing, and utilizing JSON variables in Express

I've been struggling to grasp the concept of accessing and processing data using different HTTP methods like get, put, post. Currently, I have managed to retrieve JSON data and store it in a global variable. var pokemonsData; fetch('https://raw ...

Placing a list item at the beginning of an unordered list in EJS with MongoDB and Node.js using Express

What I've done: I already have knowledge on how to add an LI to UL, but it always goes to the bottom. What I'm trying to achieve: Add an LI to the top so that when my div.todos-wrapper (which has y-oveflow: hidden) hides overflow, the todos you a ...

Creating unique div IDs dynamically in PHP, JavaScript, and MySQL

I'm currently working with an ajax code that fetches data from table columns when a specific data is selected from the dropdown menu. In my surveycontent.php file, I have the following script: <script type="text/javascript"> function show ...

Error in Vue component when setting the background image URL

Here is my code snippet that sets the background image for a component: style() { return { "background-image": `url(${require(`../../../assets/images/${this .last_result}.png`)})` }; }, The expected URL should be ../../../assets/images/ ...

Encountering an uncaught error event while using Yeoman

Whenever I try to run Yeoman, I encounter the following error: events.js:72 throw er; // Unhandled 'error' event ^ Error: spawn ENOENT at errnoException (child_process.js:1001:11) at Process.ChildProcess._handle.one ...

Retrieve main page elements from an additional page called PageSlide

I have implemented the jquery PageSlide plugin as a menu feature on my website. The plugin opens a separate page on the side of the main page to function as a menu. However, I am facing a challenge in accessing the main page's elements from this side ...