从PHP文件刷新Google地图中的纬度和经度

3

我是一名新手,第一次接触StackOverflow和编程。您好!

我想知道如何在JavaScript的Google地图上刷新PHP数据的经纬度,因为经纬度每秒钟都在变化,我想实时刷新经纬度。但问题是只有在第一次加载真实位置时才会加载,并且仅刷新相同的经纬度。如何在不重新加载页面的情况下从PHP中加载经纬度?

在这个文件中,PHP的代码段负责加载Google地图。

    <script>
  function initMap() {
  var myLatlng = new google.maps.LatLng('.json_encode($Lat).', '.json_encode($Long).');
var mapOptions = {
zoom: 13,
center: myLatlng
    }
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
    });

marker.setMap(map);
setInterval( function(){ 

    marker.setPosition( new google.maps.LatLng( '.json_encode($Lat).', '.json_encode($Long).' ) );
    map.panTo( new google.maps.LatLng( '.json_encode($Lat).', '.json_encode($Long).' ) );

    }, 1000 );
}

</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=myapikey&callback=initMap">
</script>
1个回答

0

我听到的问题:

如何根据由php脚本提供的更改坐标异步加载谷歌地图位置?

建议的解决方案:

我认为实现这一点的最佳方法是创建一个单独的php脚本,以json格式提供更新的坐标。然后在一个单独的php脚本中使用fetch从JavaScript中获取坐标。您可以在setInterval函数内运行此操作。

您的新php脚本将以以下方式结束:

echo json_encode(array('latitude' => $Lat, 'longitude' => $Lon));

然后在你的 setInterval 内部,你可以这样做:

setInterval( function(){ 
  fetch(`newphpscript.php`)
    .then((response) => response.json())
    .then((data) => {
      marker.setPosition(new google.maps.LatLng(data.latitude, data.longitude));
      map.panTo( new google.maps.LatLng(data.latitude, data.longitude ));
  });
}, 1000 );

如果您需要进一步的澄清,请留言评论。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接