function initialize(final) {
/* ........ */
var address_array = final.split('~');
for (var count = 0; count < address_array.length; count++)
{
if (geocoder) {
geocoder.getLatLng(
address_array[count],
function (point) {
if (!point) {
alert(address_array[count] + " not found");
}
All I want is the alert to work over here, in the last line.
Suppose address_array has 3 values, i.e address_array.length is 3. But the alert is always showing undefined not found. I am assuming address_array[count] cannot be accessed from this function. However when I try
alert(address_array.length + " not found");
it says 3 not found. please help.
can anyone please help me regarding this issue?
function makeTheFunction(array, thisCount) {
return function (point) {
if (!point) {
alert(array[thisCount] + ” not found”);
}
else {
var marker = new GMarker(point);
map.addOverlay(marker);
GEvent.addListener(marker, "click", function () {
marker.openInfoWindowHtml(array[thisCount] + "</b>");
});
}
};
}
the alert(array[thisCount] + ” not found”); is working fine but it doenst seem to work when it goes into the else section ..marker.openInfoWindowHtml(array[thisCount] + “”);
This happens because your function is a closure over the
countvariable, and closures get an enduring reference to the variable, not a copy of its value as of when the function is defined. So all copies of the function seecountas of the end of the loop, which is outside the range of the array — hence theundefined.What you want to do is create the function such that it closes over something that doesn’t change.
We pass both the array reference and the
countvalue as of each iteration of the loop intomakeTheFunction, which creates the function as a closure over its arguments and returns that function. Now the function will show the right information, because the information it’s closing over doesn’t change. Note that as written,makeTheFunctioncan be outside of any other function so as to avoid having the closure close over anything else.More about closures: Closures are not complicated