【问题标题】:Auto update Google Map from database从数据库自动更新谷歌地图
【发布时间】:2017-03-23 11:54:40
【问题描述】:

我有一个填充了纬度和经度的 MySQL 数据库。

数据在 Google 地图上绘制成折线。 一切正常,但我不知道如何在添加新数据时自动更新折线。

我尝试在函数 initmap 上设置间隔,但没有奏效。 如果有人可以帮助我,我会很高兴。

  <!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>

【问题讨论】:

  • 您需要使用带间隔的 Ajax 请求。如果能把js代码和php代码分开就更好了

标签: javascript php mysql google-maps


【解决方案1】:

您是否教过重新加载页面以获得所需的效果,通过将 Jquery 添加到您的代码中,您可以使用此功能,这将每十秒重新加载您的浏览器,或者,您可以调用自己的方法,也许初始化地图再次重新加载所有新数据。

new PeriodicalExecuter(function(pe) {
    location.reload(true);
}, 10);

【讨论】:

  • 谢谢你的建议,但我试过了。我唯一想要改变的是折线。如果我每次都更新整个地图,那就太多了。
  • 我想知道你能不能继续打电话,flightPath.setMap(map);或者可能创建一个更新函数来调用数据库方法和绘制折线的方法,定期运行它
【解决方案2】:

我找到了解决方法。

首先,我确实喜欢 Ahmad 的建议 - 将 php 放在不同的文件中,然后进行 ajax 调用。 ajax 返回纬度和经度。

然后我做了一个删除现有折线的函数。 之后,我做了一个更新函数,由 ajax 调用。

最后,我做了一个区间函数,调用remove函数和update函数,按设定的区间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多