I am working on a small webapp that uses google maps api.
At one point I wanted to place markers and attach event listener to it.
//initialization of infowindow and markers
var points = [];
var infowindow = new google.maps.InfoWindow({
content: "1234"
});
function addInfoWindow(point){
infowindow.setContent(point.position + " " + point.title),
infowindow.open(map, point);
}
Here's the problem, when I initiate markers with
//initialize markers
{% for marker in mapMarkers %}
points[{{ marker.id }}] = new google.maps.Marker({
position: new google.maps.LatLng({{ marker.geometry.y }},
{{ marker.geometry.x }}),
map: map,
title: '{{ marker.name }}',
clickable: true
});
//add event llistener for infowindow
points[{{ marker.id }}].content = "abc"
//look here!!
google.maps.event.addListener(points[{{ marker.id }}], 'click',
addInfoWindow(points[{{ marker.id }}])
);
{% endfor %}
It would instantly show infowindow from the first marker. The other markers were placed but clicking on them never produce any changes.
While if I do this
google.maps.event.addListener(points[{{ marker.id }}], 'click',
function(){
addInfoWindow(points[{{ marker.id }}])
});
Stuffs works perfectly fine, infowindow only appears when marker was clicked.
My question: why is there a need to use
function(){} instead of directly using addInfoWindow. I figured it might be an issue of function invocation where addInfoWindow calls the global variable, but if that's the case, the infowindow that shows up should display information from the last marker instantiated right?
addInfoWindowneeds parameters. If you just used the function reference, it wouldn't receive any parameters.