我必须从数据库中检索特定位置的坐标,然后显示以它们为中心的地图。我的解决方案似乎无效,因为它试图打开没有坐标的地图
function readyf() {
var map;
var info;
var lat;
var lon;
function initialize() {
$.ajax({
method: "POST",
//dataType: "json", //type of data
crossDomain: true, //localhost purposes
url: "getLocation.php", //Relative or absolute path to file.php file
//data: {order: ordering},
success: function (response) {
console.log(response);
info = JSON.parse(response);
lat = info[0].lat;
lon = info[0].lon;
console.log(lat);
},
error: function (request, error) {
console.log("Error");
}
});
console.log(lat);
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(lat, lon)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
}
答案 0 :(得分:1)
您需要将地图初始化移动到成功回调中。否则AJAX请求开始,地图被初始化,然后你的成功回调用坐标激发。
function readyf() {
var map;
var info;
var lat;
var lon;
function initialize() {
$.ajax({
method: "POST",
//dataType: "json", //type of data
crossDomain: true, //localhost purposes
url: "getLocation.php", //Relative or absolute path to file.php file
//data: {order: ordering},
success: function (response) {
console.log(response);
info = JSON.parse(response);
lat = info[0].lat;
lon = info[0].lon;
console.log(lat);
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(lat, lon)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
},
error: function (request, error) {
console.log("Error");
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
}