问题
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
?
回答1:
It seems that the solution was to split everything in separate functions.
function showAddress() {
//geocoder = new Geocoder();
for (var i = 0; i<addresses.length; i++)
{
var address = addresses[i];
var url = urls[i];
findAddress(address,url);
pausecomp(400);
}
}
function findAddress(address,url)
{
geocoder.geocode(
{ 'address' : address },
function(result, status) {
var marker;
if(status == google.maps.GeocoderStatus.OK) {
marker = new google.maps.Marker({
position: result[0].geometry.location,
map: map,
title:"Longueuil"
});
}
attachUrl(marker, url);
}
);
}
function attachUrl(marker, url)
{
google.maps.event.addListener(marker, 'click', function(event){
alert(url);
window.open(url);
},false);
}
My guess is that function calls create persistent copies of the values held by the variables and not merely pointers to them.
来源:https://stackoverflow.com/questions/6171664/javascript-closure-with-google-maps-geocodergeocode