从我的对象PolygonExtend我可以触发一些内部动作,如show和hide。这些行动似乎运作良好。但是,当我在click事件(google.maps.event.addDomListener)中运行相同的操作时,我得到一个“TypeError:this.name is undefined”。我怎样才能让它发挥作用?
var mapOptions = {
center: new google.maps.LatLng(4.7102000, -74.0308118),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var coords = [
{lat: 4.711177836295898, lng: -74.03219819068909},
{lat: 4.710354506576612, lng: -74.03219819068909},
{lat: 4.710354506576612, lng: -74.03176367282867},
{lat: 4.711177836295898, lng: -74.03176367282867}
];
function PolygonExtend(name, path) {
//this.name = name;
this.path = path;
this.name = new google.maps.Polygon({
path: this.path,
});
this.show = function() {
this.name.setMap(map);
};
this.hide = function() {
this.name.setMap(null);
};
return this.name.setMap(map); // makes Polygon show when instantiated
}
a = new PolygonExtend('a', coords); // works and renders Polygon
a.hide(); // works, hides Polygon
a.show(); // works, makes Polygon visible again
var btn = document.getElementById('btn');
google.maps.event.addDomListener(btn, 'click', a.hide); // TypeError: this.name is undefined
答案 0 :(得分:3)
正如上面的评论所述,这样做(如果你还没有尝试过这个解决方案)
function PolygonExtend(name, path) {
//this.name = name;
var self = this;
this.name = new google.maps.Polygon({
path: path,
});
this.show = function() {
self.name.setMap(map);
};
this.hide = function() {
self.name.setMap(null);
};
return this.name.setMap(map); // makes Polygon show when instantiated
}
答案 1 :(得分:0)
我不确定你要做什么。看起来像浪费代码,但看看这个:
function PointlessPolygon(map, coords){
var t = this;
this.map = map; this.coords = coords; this.showing = true;
this.polygon = new google.maps.Polygon({paths:t.coords});
this.show = function(){
this.polygon.setMap(map); this.showing = true;
};
this.hide = function(){
this.polygon.setMap(); this.showing = false;
}
this.polygon.setMap(map); // makes Polygon show when instantiated
}
var pp = new PointlessPolygon(map, coords);
var btn = document.getElementById('btn');
btn.addEventListener('click', function(){
pp.showing ? pp.hide() : pp.show();
});