简体   繁体   中英

How do I bind a google maps geocoder.geocode() callback function

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

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: function (location) {

    _.bind(this.setMapLocationCallback, this);

    console.log(this);

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

},

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'});
    }
},

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.

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?

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

Thanks in advance, David

try changing

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

using call() , so you can change the scope of this inside setMapLocationCallback

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

MDN Documentation about call() function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM