【发布时间】:2018-05-04 22:06:20
【问题描述】:
我正在尝试找到一种解决方案,让我可以在 Google 地图上“实时”绘制许多移动物体的 GPS 坐标。
每个对象的 GPS 坐标将不断更新到 MySQL 数据库中,我想每三秒读取一次更新的坐标,并在 Google 地图上重新绘制标记坐标,而无需用户刷新页面.
我有一个从数据库接收数据的代码,并且使用 setInterval 每 3 秒读取一次数据库信息。
我的问题在这里:每个 setinterval 加载
未读取新的数据库数据。这意味着
数据库信息被读取一次,不会收到任何新信息。
我该如何解决这个问题?
<?php
include "db_connect.php";
$sql="SELECT * FROM temperature_details ORDER BY id DESC LIMIT 1 ";
$result=mysql_query($sql);
$firstrow = mysql_fetch_assoc($result);
function getNewLat(){
$sql="SELECT * FROM temperature_details ORDER BY id DESC LIMIT 1 ";
$result=mysql_query($sql);
$lat = mysql_fetch_assoc($result);
return $lat['latitude'];
}
function getNewLang(){
$sql="SELECT * FROM temperature_details ORDER BY id DESC LIMIT 1 ";
$result=mysql_query($sql);
$Lang = mysql_fetch_assoc($result);
return $Lang['longitude'];
}
?>
<script src="http://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=geometry"></script>
<div id="map" style="height:500px;width:100%;" ></div>
<script>
function initialize() {
var myLatLng = new google.maps.LatLng({lat:<?php echo .$firstrow['latitude'];?>, lng: <?php echo .$firstrow['longitude'];?>}),
myOptions = {
zoom: 16,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map( document.getElementById( 'map' ), myOptions ),
marker = new google.maps.Marker( {position: myLatLng, map: map} );
marker.setMap( map );
moveMarker( map, marker );
}
function moveMarker( map,marker ) {
setInterval( function(){
marker.setPosition(new google.maps.LatLng( {lat:<?php echo getNewLat();?>, lng: <?php echo getNewLang();?>} ));
map.panTo( new google.maps.LatLng( {lat:<?php echo getNewLat();?>, lng: <?php echo getNewLang();?>} ));
console.log("I am working");
}, 3000 );
};
initialize();
</script>
【问题讨论】:
-
在
setInterval中,您需要对 PHP 进行 AJAX 调用以获取新标记。页面加载后 PHP 不可用,因此getNewLang是初始加载的静态值。也没有理由使用相同的查询 3 次。只需使用一次。您还应该使用PDO或mysqli更新连接到数据库的驱动程序。您当前使用的驱动程序已从新版本中删除,不支持参数化查询。 -
你能说,我该怎么做?
-
Tnx 提示@chris85。
标签: javascript php mysql google-maps google-maps-api-3