Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 718
David Erwin Avatar asked Jul 27 '26 17:07

David Erwin


1 Answers

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

like image 62
Fabrizio Calderan Avatar answered Jul 30 '26 07:07

Fabrizio Calderan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!