I am busy with a script that will make a google maps canvas on my website, with multiple markers. I want that when you click on a marker, a infowindow opens. I have done tha
I have something like the following
function initMap()
{
//...create new map here
var infowindow;
$('.business').each(function(el){
//...get lat/lng
var position = new google.maps.LatLng(lat, lng);
var content = "contents go here";
var title = "titleText";
var openWindowFn;
var closure = function(content, position){.
openWindowFn = function()
{
if (infowindow)
{
infowindow.close();
}
infowindow = new google.maps.InfoWindow({
position:position,
content:content
});
infowindow.open(map, marker);
}
}(content, position);
var marker = new google.maps.Marker({
position:position,
map:map,
title:title.
});
google.maps.event.addListener(marker, 'click', openWindowFn);
}
}
In my understanding, using a closure like that allows the capturing of variables and their values at the time of function declaration, rather than relying on global variables. So when openWindowFn
is called later, on the first marker for example, the content
and position
variable have the values they did during the first iteration in the each()
function.
I'm not really sure how openWindowFn
has infowindow
in its scope. I'm also not sure I'm doing things right, but it works, even with multiple maps on one page (each map gets one open infowindow).
If anyone has any insights, please comment.