I'm extending my previous question, because I still don't fully understand the concept of javascript closures. Take a quick look at the following code, which will put two markers on a map. (The code is slightly modified from my previous question).
var map = google.maps.somefunctoinstantiatemap();
var address = new Array();
address[0] = '1 Smith Street';
address[1] = '2 Smith Street';
function onpageload()
{
for(var rownum=0; rownum<address.length; rownum++)
{
geocoder.geocode({
'address': address[rownum]
}, function(results, status) {
geocodeCallBack(results,status,rownum)
});
}
}
function geocodeCallBack(results, status, argnum)
{
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: 'arg: '+argnum+' addr:'+results[0].formatted_address
});
google.maps.event.addListener(marker, 'click', function(){
var infowindow = new google.maps.InfoWindow({
content: marker.title
});
infowindow.open(map, marker);
});
}
Ok, multiple choice....what is the result when user clicks on both markers?
- first marker displays 'arg: 0 addr: 1 Smith Street' and second marker displays 'arg: 1 addr: 2 Smith Street'
- first marker displays 'arg: 0 addr: 2 Smith Street' and second marker displays 'arg: 1 addr: 2 Smith Street'
- first marker displays 'arg: 1 addr: 1 Smith Street' and second marker displays 'arg: 1 addr: 2 Smith Street'
- first marker displays 'arg: 1 addr: 2 Smith Street' and second marker displays 'arg: 1 addr: 2 Smith Street'
- first marker displays 'arg: undefined addr: undefined' and second marker display 'arg: undefined addr: undefined'
When I run the code, the answer is 3. But I was expecting the answer to be either 4 or 5. Why is it not 4 and why is it not 5?
forloop up top is looping three, not two, times. Also, you seem to have plucked amapvariable out of nowhere (nowhere you show, anyway).