在 JavaScript 中,我认为您不能显式暂停执行并等待回调完成,如此处所述:jQuery:等待函数完成以继续处理? 如果您有一些依赖于获取位置回调结果的逻辑,为什么不直接调用该逻辑作为回调的一部分呢?您不需要明确地等待它。关于你想要完成的事情,你正在寻找这样的东西吗?
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 });
然后,您通过this
关键字访问回调中的 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);
}