Javascript 如何从异步php数据库搜索向地理编码器发送地址
我正试图让我的谷歌地图应用程序等待来自使用php的数据库调用的ajax调用的响应。我知道我需要使用回调,但我不确定在这种情况下如何实现它们,因为geocoder api也是异步的 我尝试了来自和的答案,但我不确定如何编辑它来处理我的案例 db.phpJavascript 如何从异步php数据库搜索向地理编码器发送地址,javascript,php,ajax,google-maps-api-3,google-geocoding-api,Javascript,Php,Ajax,Google Maps Api 3,Google Geocoding Api,我正试图让我的谷歌地图应用程序等待来自使用php的数据库调用的ajax调用的响应。我知道我需要使用回调,但我不确定在这种情况下如何实现它们,因为geocoder api也是异步的 我尝试了来自和的答案,但我不确定如何编辑它来处理我的案例 db.php $mysqli = new mysqli("host", "user", "pass", "db"); (perform query)... echo json_encode($result_assoc_array); location.php
$mysqli = new mysqli("host", "user", "pass", "db");
(perform query)...
echo json_encode($result_assoc_array);
location.php
<html>
(html boilerplate)...
<body>
<div id="map"></div>
<script>
var map;
var homeAddress;
var oReq = new XMLHttpRequest();
oReq.onload = function() {
homeAddress = JSON.parse(this.responseText).address; //main field I want is address
};
oReq.open("get", "db.php", true);
oReq.send();
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: -34.397, lng: 150.644 },
zoom: 15,
});
var bounds = new google.maps.LatLngBounds();
var geocoder = new google.maps.Geocoder();
var markers = [];
geocoder.geocode({
'address': JSON.stringify(homeAddress)
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results);
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
bounds.extend(marker.position);
markers.push(marker);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
(more logic)
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=myKey&callback=initMap&libraries=geometry" async defer></script>
</body>
</html>
这应该会给我一个以db地址为中心的映射,但我得到的地理编码没有成功,原因如下:由于homeAddress未定义,因此请求无效。将ajax请求放在initMap中,当地址可用时,在其回调函数中调用地理编码程序:
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: -34.397, lng: 150.644 },
zoom: 15,
});
var bounds = new google.maps.LatLngBounds();
var geocoder = new google.maps.Geocoder();
var markers = [];
var oReq = new XMLHttpRequest();
oReq.onload = function() {
homeAddress = JSON.parse(this.responseText).address; //main field I want is address
geocoder.geocode({
'address': JSON.stringify(homeAddress)
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results);
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
bounds.extend(marker.position);
markers.push(marker);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
};
oReq.open("get", "db.php", true);
oReq.send();
(more logic)