我正在构建一个基于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回调函数中获取窗口小部件的上下文?还有另一种方法可以等待地图加载,然后用标记刷新它吗?