嘿,我正在使用 google maps API,目前我正在努力实现一些我认为相当简单的东西。
我的 friend 想在他的网站上安装一个访问者 map ,访问者可以在 map 上的任何点添加标记,每个标记都有与之关联的信息。姓名、日期、消息等信息......
现在我正处于原型(prototype)设计和学习阶段,但我无法将 infowindow
与 marker
对象相关联。
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);
});
}
当我测试这段代码时,标记放置得很好,但是当我点击它们时,我没有显示 InfoWindow,而是在 JS 控制台中收到此错误:
Uncaught TypeError: Cannot call method 'open' of undefined
当然这是一个范围问题,但我不明白为什么会这样。像这样的东西很好用:
function test(a){
this.a = a
this.b = function(){
this.a+=1
}
}
非常感谢您的帮助!
最佳答案
看起来你在这里失去了范围:
google.maps.event.addListener(this.mark, 'click', function(){
this.info.open(map, this.mark);
});
尝试像这样存储 this
的值:
var _self = this;
google.maps.event.addListener(_self.mark, 'click', function(){
_self.info.open(map, _self.mark);
});
关于使用 Google Maps API 时的 Javascript 作用域问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7294703/