这里我试图在数据库中3秒后更新标记,我只是尝试在没有页面加载的数据库中在谷歌地图中运行时添加标记。我认为问题来自<div>
标签,最初标记出现但是当ajax_call()出现时页面没有显示任何内容。我不是一个优秀的程序员,如果你发现任何代码错误,请帮忙。
<!DOCTYPE html>
<html>
</head>
<body>
<div id="map"></div>
<script>
function ajax_call() {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("map").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","ajax.php",true);
xmlhttp.send();
}
function initMap() {
// Create a map object and specify the DOM element for display.
var myLatLng = {center:new google.maps.LatLng(31.55460609999999,74.35715810000001),
zoom: 13,
scrollwheel: true,
mapTypeId: google.maps.MapTypeId.HYBRID};
var map = new google.maps.Map(document.getElementById('map'), myLatLng);
var all = <?php echo json_encode($jsArray) ?>;
// Create a marker and set its position.
for (i = 0; i < all.length; i++)
{
var myLatLng = {lat: all[i][2], lng: all[i][1]};
var marker = new google.maps.Marker({
map: map,
position: myLatLng,
animation:google.maps.Animation.BOUNCE,
title: all[i][0]
});
marker.setMap(map);}
setInterval(ajax_call, 3000);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCqGqkUbR3rvvo8QppeBBzRLUgEIduwmis&callback=initMap"
async defer>
</script>
</body>
</html>
和ajax.php代码是:
<?php
$sql = "SELECT PhoneId, longitude, latitude FROM Clients";
$result = $conn->query($sql);
$all = array();
$r = 0;
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$c = 0;
$all[$r][$c] = $row["PhoneId"];
$c++;
$all[$r][$c] = $row["longitude"];
$c++;
$all[$r][$c] = $row["latitude"];
$r++;
}
$jsArray = array();
foreach ($all as $array) {
$jsArray[] = array($array[0], (double) $array[1], (double) $array[2]);
}
} else {
echo "0 results";
}
$conn->close(); ?>
<!DOCTYPE html>
<html>
<body>
<script>
var all = <?php echo json_encode($jsArray) ?>;
// Create a marker and set its position.
for (i = 0; i < all.length; i++)
{
var myLatLng = {lat: all[i][2], lng: all[i][1]};
var marker = new google.maps.Marker({
map: map,
position: myLatLng,
animation:google.maps.Animation.DROP,
title: all[i][0]
});
marker.setMap(map);}
</script>
</body>
</html>