开发者

Javascript Scope problem when using Google Maps API

Hey I'm fooling around with google maps API, and at the moment I am struggling to implement something that I would think would be fairly straight forward.

My friend wants to have one of those visitor map things on his site where visitors can add a marker to any point on the map, and with each marker there will be information associated with it. Information such as name, date, message, etc....

Right now I am in the prototyping and learning stage, but I am having trouble associating an infowindow with a marker o开发者_运维知识库bject.

var map;
var markers = []
function init(){
        var latlng = new google.maps.LatLng(-44, 140);
        var myOptions = {
                zoom:8,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);


        google.maps.event.addListener(map, 'click', function(event){
            markers.push(new marker(event.latLng));
        });
}

function marker(location){
    this.location = location;
    this.mark = new google.maps.Marker({position:this.location, map:map});
    this.info = new google.maps.InfoWindow({content:'hi'});
    google.maps.event.addListener(this.mark, 'click', function(){
        this.info.open(map, this.mark);
    });
}

When I test this code out the markers are placed fine, but when I click on them, instead of displaying the InfoWindow I get this error in the JS console:

Uncaught TypeError: Cannot call method 'open' of undefined

Certainly this is a scope problem, but I can't understand why that should be. Something like this works fine:

function test(a){
    this.a = a
    this.b = function(){
        this.a+=1
    }
}

Thanks a lot for the help!


Looks like you're losing scope here:

google.maps.event.addListener(this.mark, 'click', function(){
  this.info.open(map, this.mark);
});

Try storing the value of this like so:

var _self = this;    
google.maps.event.addListener(_self.mark, 'click', function(){
  _self.info.open(map, _self.mark);
});


One way of achieving what you want to could be by passing this.info as argument to the function which you are associating with the click event and then using 'open' on the parameter passed. This should resolve the issue.

The reason for why this function is not being able to identify this.info is that the function is not being defined as an inner function here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜