Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何绑定google maps geocoder.geocode()回调函数_Javascript_Google Maps_Backbone.js - Fatal编程技术网

Javascript 如何绑定google maps geocoder.geocode()回调函数

Javascript 如何绑定google maps geocoder.geocode()回调函数,javascript,google-maps,backbone.js,Javascript,Google Maps,Backbone.js,我有一个视图,其中包含一个谷歌地图,可在视图范围内通过this.map访问。世界上一切都好 接下来,我想通过视图中的事件更新地图位置。为此,我采用文本输入,使用google.maps.Geocoder.geocode(),然后通过以下方式更新位置: setMapLocation:函数(位置){ 这里的console.log(this)向我显示了视图的范围,可以正确访问this.map。请注意,我在这里显式地将回调绑定到它。下面是回调: setMapLocationCallback: functi

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

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

setMapLocation:函数(位置){

这里的console.log(this)向我显示了视图的范围,可以正确访问this.map。请注意,我在这里显式地将回调绑定到它。下面是回调:

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'});
    }
},
问题在于,在回调控制台中.log(this)显示这是窗口对象的作用域,即使我将其显式绑定到视图对象的this作用域

我需要在回调中访问this.map,因为我可能在一个页面上有多个映射,并且需要区分我正在谈论的映射

如何将此回调绑定到适当的范围?或者,有更好的方法吗

我正在使用backbonejs和下划线JS,但这应该是一个相当普遍的问题

提前感谢,, 大卫

试着改变一下

 geocoder.geocode({'address': location}, this.setMapLocationCallback);
使用
call()
,因此您可以在
setMapLocationCallback

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

这就成功了!谢谢你,先生!我一直听说在即将发布的js版本中,这类事情是由“直觉”语法处理的。我期待着看到结果。与此同时,在ECMAScript 5中,他们发明的方法正是针对这种情况:你在一个函数上调用它,它会创建一个新函数,其中“this”具有传递给bind()的值。它保存了变量this和实际回调setMapLocationCallback周围的包装函数。这里的整个内容将变成
geocoder.geocode({'address':location},this.setMapLocationCallback.bind(this));
问题中的代码不起作用,因为geocode只记住它应该调用的函数,而不记住它的作用域(this值)。即使您给出
this.setMapLocationCallback
,它也只记住setMapLocationCallback。因此,一些API接受一个额外的作用域参数。同时
bind()
被发明用来传递函数及其作用域。
 var _this = this;
 geocoder.geocode({'address': location}, function(result, status) {
     _this.setMapLocationCallback.call(_this, result, status);
 });