2

I'm working on an application that uses the Google Maps API. I have no prior experience with javascript. What I'm trying to do is the following:

function SpeedMarker(position) {
    this.speed = 50;
    this.marker = new google.maps.Marker({
        position: position,
        map: map,
        icon: 'http://maps.google.com/mapfiles/markerA.png',
        zIndex: Math.round(position.lat() * -100000) << 5
    });
    google.maps.event.addListener(this.marker, 'click', this.ShowInfoWindow)        
}

SpeedMarker.prototype.ShowInfoWindow = function () {
    var contentString = 'stuff';
    infowindow = new google.maps.InfoWindow({
        content: contentString
    });
    infowindow.open(map, this.marker);
}

The issue is that the click event happens in the document object, and this.marker does not exist in that context.

Is there any way to handle the event within the SpeedMarker object I created?

1 Answer 1

5

Change

google.maps.event.addListener(this.marker, 'click', this.ShowInfoWindow);

to

var self = this;
google.maps.event.addListener(this.marker, 'click', function () {
    self.ShowInfoWindow();
});

or use Function.bind (warning: may require shim):

google.maps.event.addListener(this.marker, 'click', this.ShowInfoWindow.bind(this));
Sign up to request clarification or add additional context in comments.

3 Comments

OK, So this might be specific to google maps but here's what happens when I run the code above (not the Function.bind): -the handler gets called when I invoke the constructor, without me clicking the marker (this does not happen if I use the original version with an alert) -if I try to run this handler later on I get an error from google maps saying: unable to find the property 'xx', (I'm guessing because I am no longer in the map context so this.xx does not exist)
I'm guessing you missed the anonymous function, and are passing something like this: ...addListener(this.marker, 'click', self.ShowInfoWindow()); ...which is not right.
[psychic-powers-activate] :)

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.