riddle: the worth inside the sealed envelope alters

When it comes to geocoding, I rely on

http://tile.cloudmade.com/wml/latest/web-maps-lite.js
.

I have an array filled with approximately 20 addresses.

addresses[n] = {where:where,who:who,contact:contact,note:note,type:type};

My process involves looping through this array for geocoding purposes.

for (var i = 0; i < addresses.length; i++) {
    geocoder2.getLocations(addresses[i].where, function(response) { //a callback
       return function(k){
       Lat[k] = response.features[0].centroid.coordinates[0];
       Lng[k] = response.features[0].centroid.coordinates[1];
       latlng = new google.maps.LatLng(Lat[k], Lng[k]);
        MarkerArray[k] = new google.maps.Marker({
          map: map,
          position: latlng,
          zIndex: k,
          title: addresses[k].who,
          icon: icons(addresses[k].type.trim())
        });}(i) // a closure function called
    });
}

Despite the setup, I keep encountering an issue where it only works on the final index. Why could that be?

Answer №1

You are facing the Closure Loop Problem. Your attempt to solve it by inserting the return function(k)... closure is not working because it is inside the callback function. Therefore, it will only execute once the loop has finished and i is at its final value.

To resolve this issue, you need to move that wrapper outside of the loop so it is directly within the loop:

for (var i = 0; i < addresses.length; i++) {
    geocoder2.getLocations(addresses[i].where, function(k) { //a callback
        return function(response){
            Lat[k] = response.features[0].centroid.coordinates[0];
            Lng[k] = response.features[0].centroid.coordinates[1];
            latlng = new google.maps.LatLng(Lat[k], Lng[k]);
            MarkerArray[k] = new google.maps.Marker({
                map: map,
                position: latlng,
                zIndex: k,
                title: addresses[k].who,
                icon: icons(addresses[k].type.trim())
            });
        }
    }(i)); // binding *here* instead!
}

Alternatively, you can utilize Function#bind to avoid using a nested function.

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

JavaScript allows for the immediate termination of CSS animations

I am currently working on an input box that has a CSS animation applied to it. This animation creates a smooth fade-in effect when the page is loaded. Here is the CSS code: #search-box { /* ... */ animation: 2s fade-in } @keyframes fade-in { ...

Executing a quick shallow copy of an object in a single ReactJS operation

I have an object in a component that I need to copy to a property. Currently, I am achieving this as follows: onSubmit: values => { data.label = values.label; data.userName = values.userName; data.recipientUserName = values.recipient ...

Error encountered: "selenium.common.exceptions.WebDriverException: Message: An error occurred - the script should be of type string when using the execute_script() function with Selenium in Python"

I'm currently facing a problem with browser.execute_script in my Selenium Python script. I have an element that I need to click on, which has the following xpath: "//*[@id='listFav_FI410_23244709400000_FAGNNURROR_IPOF_APP_P43070_W43070A_CP000A00 ...

Submitting the form with an extending controller results in an undefined state

I have a primary controller and another controller where I extend the primary one to display a different layout. Primary controller: function CustomerInformationController(...) { var vm = this; ... vm.save = function() { if (angular. ...

Issues encountered when trying to execute npm start: "The function this.htmlWebpackPlugin.getHooks is not recognized."

My background in web development is weak, and I'm facing a challenging situation. I had to take over the work of a colleague who left, and now I'm trying to finish the site we were working on. Since then, I've been learning about web develop ...

Slideshow Display Suddenly Halts at the Last Image

I am currently working on a Bootstrap JS Carousel that showcases several images stored in the project folder. Each image's filepath is retrieved from an SQL Server database and displayed within the carousel. While the images are displaying correctly ...

Guide on catching network errors using Axios request interceptor?

After encountering issues with our Vue application, I observed in the Sentry logs that the problem may stem from an unreliable network: Error: Network Error Error: Request aborted I wanted to display a warning message to the user but couldn't find a ...

ReferenceError: _jquery2.default.ajax is not a function" encountered in a React Native application

I have been attempting to use jQuery to retrieve xml data from an internal website. My expo project setup is quite basic and resembles the following: import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; imp ...

Steps for selecting checkboxes according to database values in AngularJSWould you like to learn how to automatically check checkboxes based on the

I am experiencing an issue where I can successfully insert values into the database based on what is checked, but I am encountering difficulty retrieving the values when fetching from the database. Can anyone provide me with some assistance? Thank you. Th ...

Reloading the page silently in the background

Upon a successful http request, I need to update the page outside of ng-view without notifying the user. Currently, I am using $window.location.reload() which works correctly. However, I want to reload the page silently so that the user does not notice a ...

What is the best way to customize the border color of a disabled Material UI TextField?

I'm struggling to override the default style for disabled Mui TextField components, particularly in changing the border color. Although I successfully altered the label color for disabled fields, I can't seem to get the border color to change. T ...

Concerns have been raised regarding the lack of light and shadows being detected by THREE.BufferGeometry in JavaScript/th

I've been trying to generate terrain using noise functions, but I'm running into an issue where the BufferGeometry mesh isn't receiving any light from PointLight. When I switch to AmbientLight, the BufferGeometry is visible, but not with Poi ...

Troubleshooting issues with the 'date' input type feature on mobile devices

When I use the following code: <input type='month' ng-readonly='vm.isReadonly' required min="{{vm.threeMonthsAgo}}" max='{{vm.oneMonthAhead}}'/> I am experiencing some difficulties on mobile devices that do not occur o ...

Ways to transfer the value of a JavaScript variable to a PHP variable

Similar Question: How can I transfer JavaScript variables to PHP? I am struggling to assign a JavaScript variable to a PHP variable. $msg = "<script>document.write(message)</script>"; $f = new FacebookPost; $f->message = $msg; Unfort ...

Occasionally, data may fail to be fetched when using a Jquery GET

Here's what I've narrowed it down to: $.getJSON('/drinks/getColors', function(items) { colors = items; }); $.each(colors, function(index2, value2) { if (value.name == value2.name) { curColor = value2.color; } }); ...

Tips for including an additional class in an element

I have an image tag with the "kiwi" class, and another class that makes it spin. I want to toggle this second class (called 'elem') when clicking on the play button of my music player. Here is the image tag with the class: <img src="./im ...

Perform the multiplication operation on two values retrieved from the API response and then calculate the total sum

I am currently pulling information from an API and I'm looking to perform a calculation on the data. Specifically, I want to multiply two different values from the response and then sum up the totals. While I already know how to sum all the values usi ...

Retrieving a time series data set from a JSON stream

Even though ThingSpeak offers great charts, I'm interested in retrieving data from ThingSpeak and creating my own visualizations using Google Charts. When extracting a "feed" from ThingSpeak, the data is presented in a JSON object like the one below: ...

Using Jquery's append() method to dynamically alter the HTML content

I am attempting to create a table with rows that are added dynamically. The challenge I am encountering is that each row consists of form elements, including multiple inputs. I have a PHP function that generates the correct row, and I have been able to sen ...

exchanging the positions of two animated flipdivs

Hey there! I'm facing a little challenge with my two divs (let's call them div1 and div2). One of them has a flip animation on hover, while the other flips on toggle click. My goal is to swap these two divs by dragging and dropping them. I' ...