我目前正在为 Google Map API GeoCoding 构建一个简单的示例应用程序,并偶然发现了 javascript 的问题。
geocodeRequest 方法应将其结果值分配给变量 this.tempResult。但是,当我尝试在 Listener 中打印它时,该变量为空。
控制台的输出是:
- 听众:空
- geoCodeRequest:对象
打印输出的顺序似乎意味着 Listener 中的代码在 geoCodeRequest 方法设法分配 this.tempResult 变量之前提前运行。
有解决方案吗?
$JSKK.Class.create
(
{
$namespace :'application',
$name :'GeoCoder'
}
)
(
{
},
{
service :null,
main :null,
geoCodeInput: null,
geoCodeButton: null,
reverseGeoCodeButton: null,
reverseGeoCodeActive: null,
callback :null,
reverseCallback:null,
tempResult: null,
init: function(main, callback, reverseCallback)
{
this.main = main;
this.callback = callback;
this.reverseCallback = reverseCallback;
this.service = new google.maps.Geocoder();
this.geoCodeInput = $('#toolPannel div[data-resource=locator] input[data-action=input]');
this.geoCodeButton = $('#toolPannel div[data-resource=locator] input[data-action=geocode]');
this.reverseGeoCodeButton = $('#toolPannel div[data-resource=locator] input[data-action=reversegeocode]');
this.reverseGeoCodeActive = false;
this.createListener();
},
geoCodeRequest: function(request)
{
this.service.geocode
(
request,
function (result,status)
{
//console.debug(arguments);
if (status== google.maps.GeocoderStatus.OK)
{
this.tempResult = result[0];
console.debug(this.tempResult);
}
else
{
alert ('GeoCoder request failed!');
}
}.bind(this)
);
},
createListener: function()
{
this.geoCodeButton.click(function()
{
this.geoCodeRequest
(
{
address: this.geoCodeInput.val()
}
);
this.callback(this.tempResult);
}.bind(this) //Bind here
);
this.reverseGeoCodeButton.click(function()
{
if (!this.reverseGeoCodeActive)
{
this.main.map.setOptions({draggableCursor:'crosshair'});
this.reverseGeoCodeActive=true;
}
else if(this.reverseGeoCodeActive)
{
this.main.map.setOptions({draggableCursor:'hand'});
this.reverseGeoCodeActive=false;
}
}.bind(this)
);
google.maps.event.addListener
(
this.main.map,
'click',
function (event)
{
if (this.reverseGeoCodeActive)
{
this.geoCodeRequest
(
{
location: event.latLng
}
);
console.debug(this.tempResult);
this.reverseCallback(this.tempResult);
}
}.bind(this)
);
}
}
);