我如何绑定一个谷歌地图的地理coder.geo code()回调函数 [英] How do I bind a google maps geocoder.geocode() callback function

查看:377
本文介绍了我如何绑定一个谷歌地图的地理coder.geo code()回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a view that contains a google map accessible via this.map within the view scope. All is well in the world.

接下来,我想通过更新在我看来,事件的地图位置。要做到这一点,我需要文本输入,可使用google.maps.Geo coder.geo code(),然后通过更新的位置是:

Next I want to update the map position via events in my view. To do this I take text input, use google.maps.Geocoder.geocode(), then update the position via:

setMapLocation:功能(位置){

setMapLocation: function (location) {

    _.bind(this.setMapLocationCallback, this);

    console.log(this);

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

},

的console.log(本)的这里表明我的观点的范围,用的 this.map 的正常访问。请注意,我的回调明确绑定到这个位置。这里的回调:

The console.log(this) here shows me the scope of the view, with this.map properly accessible. Notice that I explicitly bind the callback to this here. Here's the callback:

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(本)的显示,这个的作用范围是Window对象的即使我约束它明确​​视图对象的这个范围。

The problems is that inside the callback console.log(this) shows that this is scoped to the Window object even though I bound it explicitly to the view object's this scope.

我需要访问this.map回调,因为我可能有一个页面上的多个地图,需要区分我说的是哪一个。

I need to access this.map in the callback because I may have more than one map on a page and need to distinguish which one I'm talking about.

如何绑定这个回调到合适的范围是什么?或者,有没有更好的方法来做到这一点?

How do I bind this callback to the proper scope? or, is there a better way to do this?

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

I'm using backbonejs and underscorejs, but this should be a fairly generic problem.

在此先感谢,
大卫

Thanks in advance, David

推荐答案

请尝试更改

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

使用()调用,所以你可以改变这个 setMapLocationCallback范围

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

MDN有关调用文档()函数

这篇关于我如何绑定一个谷歌地图的地理coder.geo code()回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆