我正在构建一个小部件,它将基于 Google Maps API 创建地图。我很难在事件侦听器中使用小部件的上下文。这是我的代码:
(function( $ ) {$.widget( "al.Mappable", {
options: {
lat: null,
lng: null,
bounds: null,
verbose: true,
showMap: true,
googleMap: {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
},
googleMap: null,
self: null,
_create: function() {
this.debug("create widget");
self: this,
this._setupMap = $.proxy(this._setupMap, this);
if (this.options.showMap){
this._setupMap();
}
},
_setupMap: function(){
this.debug("init map");
// debugger;
if(this.options.lat && this.options.lng){
this.options.googleMap.center = this._latLng(this.options);
}
else{
//kaboom address
this.options.lat = 38.945596;
this.options.lng = -77.064773;
this.options.googleMap.center = this._latLng(this.options);
}
this.googleMap = new google.maps.Map(this.element[0], this.options.googleMap);
this._addUserLocation(38.945596,-77.064773);
google.maps.event.addListenerOnce(this.googleMap, 'tilesloaded',this._refreshMap(this.googleMap) );
},
_refreshMap: function(gmap){
bounds = gmap.getBounds()
this.options.bounds = bounds
dataOptions ={
searching: true,
keyword: getParam('keyword'),
playspace_type: getParam('playspace_type'),
location_type: getParam('location_type'),
bounds: bounds.toUrlValue()
}
// note the 'dummy event' in the callback since ujs sends the event as the first argument
// $.ajax "/playspaces/search.js",
// context: this
// data: dataOptions
// dataType: 'json'
// success: (data,status,xhr) -> @afterResultsAjax('dummyevent',data,status,xhr, false)
},
_latLng: function(opt){
return new google.maps.LatLng(opt.lat,opt.lng);
},
});
}( jQuery ));
当我这样做("#map").mappable()
时,我得到错误,因为边界是undefined
并且toUrlValue()
正在引发错误。解释是bounds = gmap.getBounds()
在触发事件之前tileloaded
触发。
我试图这样做:
google.maps.event.addListenerOnce(this.googleMap, 'tilesloaded', function(){
console.log(this);
});
我得到了googleMap object
后面而不是widget object
。我努力了:
google.maps.event.addListenerOnce(this.googleMap, 'tilesloaded', function(){
console.log(self);
});
我得到了window
对象。
问题:
如何在 eventListener 回调函数中获取小部件的上下文?有没有另一种方法来等待地图加载然后用标记刷新它?