我试图从JQuery函数中检索数据并将其传递给全局变量以与Google Maps一起使用。这些变量必须保持全球化,否则谷歌地图不会与它们合作。我设法从AJAX url获取我需要的所有数据,并且它只在Jquery函数内完美记录。如果我将它记录在它之外,它是未定义的。无论如何都要将这些值传递给全局变量吗?
function displayMarkers() {
var latlng = new google.maps.LatLng(latitd, longtd);
var name = titleName;
createMarker(latlng, name);
}
var latitd;
var longtd;
var titleName;
$(document).ready(function() {
$('#earthquakes').click(function() {
getQuakes();
});
function getQuakes() {
$.ajax({
url: 'http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=' + yesterDate + '&endtime=' + displayDate,
success: function(data) {
console.log(data);
$.each(data.features, function(key, val) {
var coord = val.geometry.coordinates;
locationD = {
latd: coord[0],
lngd: coord[1]
};
latitd = locationD.latd;
longtd = locationD.lngd;
titleName = val.properties.title;
console.log(latitd, longtd);
console.log(titleName);
});
}
});
}
});
答案 0 :(得分:1)
您的代码应该是这样的
var latitd;
var longtd;
var titleName;
$(document).ready(function () {
$('#earthquakes').click(function () {
getQuakes();
});
});
function getQuakes() {
$.ajax({
url: 'http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=' + yesterDate + '&endtime=' + displayDate,
success: function (data) {
console.log(data);
$.each(data.features, function (key, val) {
var coord = val.geometry.coordinates;
locationD = {
latd: coord[0],
lngd: coord[1]
};
latitd = locationD.latd;
longtd = locationD.lngd;
titleName = val.properties.title;
console.log(latitd, longtd);
console.log(titleName);
//Call this function to display here after success ajax
displayMarkers();
});
}
});
}
function displayMarkers() {
var latlng = new google.maps.LatLng(latitd, longtd);
var name = titleName;
createMarker(latlng, name);
}
答案 1 :(得分:-1)
为你的ajax请求添加async:false。
由于