I’m using google.maps javascript API v3. I need to translate a set of civic addresses to markers on a google map with ‘click’ listeners. When the user clicks on the marker in the map, I want another window to open with a url related to that address (another tab would be ideal).
I can’t manage to keep the relation between the address and the url, because I’m using javascript Closure with the google method geocode().
I have a set of addresses such as
var addresses = [ '123 street street', '124 street street' ];
var urls = [ 'www.example.com/1', 'www.example.com/2' ];
Then I use the API to geocode and create markers on the map
for (var i = 0; i<addresses.length; i++)
{
var address = addresses[i];
var url = urls[i];
geocoder.geocode(
{ 'address' : address },
function(result, status) {
var x = url // url == ""
var marker = new google.maps.Marker({
position: result[0].geometry.location,
map: map,
title:"Test"
});
google.maps.event.addListener(marker, 'click', function(event){
alert(url);
window.open(url);
},false);
}
}
inside the anonymous function, how can I use var url ?
It seems that the solution was to split everything in separate functions.
My guess is that function calls create persistent copies of the values held by the variables and not merely pointers to them.