在JavaScript中,我不認爲你可以明確地停止執行,並且等待回調結束的注意這裏:jQuery: wait for function to complete to continue processing?如果您有依賴於獲得位置回調,爲什麼不結果一些邏輯只需調用該邏輯作爲回調的一部分?你不需要明確地等待它。關於你想要完成的事情,是這樣的,你在找什麼?
var map;
function test() {
//Call GetMap() to get position
GetMap();
//Wait until callback is finished
//Do something with user's location (result of the callback)
}
function GetMap()
{
// Set the map options
var mapOptions = {credentials:"Bing Maps Key"};
// Initialize the map
map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), mapOptions);
// Initialize the location provider
var geoLocationProvider = new Microsoft.Maps.GeoLocationProvider(map);
// Get the user's current location
geoLocationProvider.getCurrentPosition({successCallback:displayCenter},{errorCallback:onError});
}
function onPositionReady(position) {
// Execute some more code with user's location
// For Example...
// Apply the position to the map
var location = new Microsoft.Maps.Location(position.coords.latitude,
position.coords.longitude);
map.setView({ zoom: 18, center: location });
// Add a pushpin to the map representing the current location
var pin = new Microsoft.Maps.Pushpin(location);
map.entities.push(pin);
}
function onError(err) {
switch (err.code) {
case 0:
alert("Unknown error");
break;
case 1:
alert("The user said no!");
break;
case 2:
alert("Location data unavailable");
break;
case 3:
alert("Location request timed out");
break;
}
}
更新: 如果你想傳遞參數到您的回調,您可以使用功能的結合來覆蓋你的回調裏面的this
關鍵字和參數傳遞這樣:
例如,如果集高達myObject
包含你的論點,你可以把它像這樣:
geoLocationProvider.getCurrentPosition({ successCallback: onPositionReady.bind(myObject) }, { errorCallback: onError });
然後,您通過訪問myObject的在回調關鍵字:
function onPositionReady(position) {
var myProperty = this.yourProperty; // this now refers to myObject
// Execute some more code with user's location
// For Example...
// Apply the position to the map
var location = new Microsoft.Maps.Location(position.coords.latitude,
position.coords.longitude);
map.setView({ zoom: 18, center: location });
// Add a pushpin to the map representing the current location
var pin = new Microsoft.Maps.Pushpin(location);
map.entities.push(pin);
}
問題是我想在回調中有一些變量,我沒有找到通過它們的方法。我不想將它們聲明爲全局變量。我不相信這是正確的解決方案。 – glarkou 2012-04-22 17:25:05
@salamis如果我正確理解你,你想要傳遞變量到回調中?如果是這樣,請看我最新的答案。 – 2012-04-22 17:45:29
非常感謝。我會嘗試。 – glarkou 2012-04-22 18:03:32