1

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?

1
  • Because addInfoWindow needs parameters. If you just used the function reference, it wouldn't receive any parameters. Commented Nov 5, 2012 at 3:04

1 Answer 1

2

Because you need to assign a function as a click handler - and you do that with...

google.maps.event.addListener(points[{{ marker.id }}], 'click',
function(){
    addInfoWindow(points[{{ marker.id }}])
});

... as this will create an anonymous function (with call to addInfoWindow in its body).

But with this...

google.maps.event.addListener(points[{{ marker.id }}], 'click',
    addInfoWindow(points[{{ marker.id }}])
);

... you try to assign the result of addInfoWindow call as event handler, not the function itself. Of course, it doesn't work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.