我有一个填充了纬度和经度的MySQL数据库。
数据在谷歌地图上像折线一样绘制。一切正常,但我不知道在添加新数据时如何自动更新折线。
我尝试在函数初始化图上设置间隔,但这不起作用。如果有人能帮我解决这个问题,我会很感激。
<!DOCTYPE html >
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(59.913063,10.750923),
zoom: 10,
mapTypeId : 'terrain'
});
var flightPlanCoordinates = [
<?php
require("dbcred.php");
$connection = mysqli_connect($host, $username, $password, $database);
mysqli_select_db($connection, $database);
$query = mysqli_query($connection,"SELECT latitude, longitude FROM geografi");
while($row = mysqli_fetch_assoc($query)){
$lat = $row['latitude'];
$lon = $row['longitude'];
echo 'new google.maps.LatLng('.$lat.', '.$lon.'),';
}
?>
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=GoogleKey&callback=initMap">
</script>
</body>
</html>
您是否教过如何重新加载页面以提供所需的效果,通过将 Jquery 添加到您的代码中,您可以使用此功能,这将每十秒重新加载一次浏览器,或者,您可以调用自己的方法,也许再次初始化映射重新加载所有新数据。
new PeriodicalExecuter(function(pe) {
location.reload(true);
}, 10);
我找到了如何做到这一点的解决方案。
首先,我按照 Ahmad 的建议做了 - 将 php 放在不同的文件中,然后进行了 ajax 调用。ajax 返回纬度和经度。
然后我做了一个函数来删除现有的折线。之后,我做了一个更新函数,由 ajax 调用。
最后,我做了一个间隔函数,按设定的间隔调用删除函数和更新函数。