gpt4 book ai didi

javascript - 如何绑定(bind) google maps geocoder.geocode() 回调函数

转载 作者:行者123 更新时间:2023-11-29 09:56:40 27 4
gpt4 key购买 nike

我有一个 View ,其中包含可在 View 范围内通过 this.map 访问的谷歌地图。世界上一切都很好。

接下来我想通过我 View 中的事件更新 map 位置。为此,我采用文本输入,使用 google.maps.Geocoder.geocode(),然后通过以下方式更新位置:

setMapLocation: 函数(位置){

    _.bind(this.setMapLocationCallback, this);

console.log(this);

var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': location}, this.setMapLocationCallback);

},

这里的 console.log(this) 向我展示了 View 的范围,this.map 可以正确访问。请注意,我在这里明确地将回调绑定(bind)到 this。这是回调:

setMapLocationCallback: function (results, status) {

console.log('this in the callback');
console.log(this);

if (status == google.maps.GeocoderStatus.OK) {
this.map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: this.map,
position: results[0].geometry.location
});
this.mapCanvas.css({visibility: 'visibile'});
} else {
this.mapCanvas.css({visibility: 'hidden'});
}
},

问题是在回调内部 console.log(this) 显示 this 的范围是 Window 对象 即使我明确地绑定(bind)了它 到 View 对象的 this 范围。

我需要在回调中访问 this.map,因为我可能在一个页面上有不止一张 map ,并且需要区分我在说的是哪一张。

如何将此回调绑定(bind)到正确的范围?或者,有更好的方法吗?

我正在使用 backbonejs 和 underscorejs,但这应该是一个相当普遍的问题。

提前致谢,大卫

最佳答案

尝试改变

 geocoder.geocode({'address': location}, this.setMapLocationCallback);

使用 call(),因此您可以在 setMapLocationCallback 中更改 this 的范围

 var _this = this;
geocoder.geocode({'address': location}, function(result, status) {
_this.setMapLocationCallback.call(_this, result, status);
});

MDN Documentation about call() function

关于javascript - 如何绑定(bind) google maps geocoder.geocode() 回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10516561/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com