请查看此代码。我希望它能够:
latitude
和longitude
)var center = new google.maps.LatLng(resplat, resplon);
问题是代码没有按此顺序执行。它“跳过”最初的Ajax并在运行其他代码时首先返回它。这使我的两个价值观无用。有人可以解释代码执行顺序背后的逻辑吗?
function Initialize() {
$.ajax({
type: "GET",
url: 'http://ip-api.com/json',
dataType: "json",
success: function (resp) {
resplat = resp.lat;
resplon = resp.lon;
}
});
// Google has tweaked their interface somewhat - this tells the api to use that new UI
google.maps.visualRefresh = true;
var center = new google.maps.LatLng(resplat, resplon);
// These are options that set initial zoom level, where the map is centered globally to start, and the type of map to show
var mapOptions = {
zoom: 15,
center: center,
mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP
};
答案 0 :(得分:1)
移动使用ajax成功回调中的resplat
和resplon
的代码:
function Initialize() {
$.ajax({
type: "GET",
url: 'http://ip-api.com/json',
dataType: "json",
success: function (resp) {
var resplat = resp.lat;
var resplon = resp.lon;
// Google has tweaked their interface somewhat - this tells the api to use that new UI
google.maps.visualRefresh = true;
var center = new google.maps.LatLng(resplat, resplon);
// These are options that set initial zoom level, where the map is centered globally to start, and the type of map to show
var mapOptions = {
zoom: 15,
center: center,
mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP
};
}
});
}
$.ajax
是异步调用。您必须等待,直到数据到来(success
处理程序)。然后你可以使用它。
另一种方法是添加.done(foo)
处理程序:
$.ajax({...}).done(function (...) { /* do something */ });