Recently, I've been working with the google.maps javascript API v3. I'm faced with a challenge of translating a collection of civic addresses into markers on a google map while also adding 'click' listeners. What I aim for is that whenever a user clicks on a marker, a new window should open displaying a URL relevant to that specific address (ideally in another tab).
Despite my efforts, I have struggled to maintain the connection between the address and its corresponding URL due to my use of a javascript Closure in conjunction with the geocode() method provided by Google.
In my list, I have several addresses like:
var addresses = [ '123 street street', '124 street street' ];
var urls = [ 'www.example.com/1', 'www.example.com/2' ];
Using the API, I proceed to geocode the addresses and place markers on the map as shown below:
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);
}
}
While working within the anonymous function, I find myself wondering how to effectively utilize var url
.