使用实时数据在谷歌地图上移动标记

时间:2016-04-01 04:02:12

标签: javascript php mysql google-maps google-maps-api-3

数据库表每20秒更新一次新数据。我不想用新的lat& amp;移动地图上的标记。郎。我尝试每隔30秒运行一次查询以获取表格的最后一条记录并更新标记的位置。映射加载,显示标记并调用javascript函数。但是标记没有移动。请帮忙..

<?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 getNewLatLang(){
$sql="SELECT * FROM temperature_details ORDER BY id DESC LIMIT 1 ";
$result=mysql_query($sql);

$latLang = mysql_fetch_assoc($result);

echo $latLang['latitude'].','. $latLang['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( <?php echo $firstrow['latitude'].','. $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( <?php echo getNewLatLang(); ?> ) );

    map.panTo( new google.maps.LatLng( <?php echo getNewLatLang(); ?>));
    console.log("I am working");

}, 30000 );

};

initialize();

</script>      

2 个答案:

答案 0 :(得分:0)

似乎是一个变量范围问题....尝试声明var map和marker

<script>

// Declare the var for global scoping visibilty
var map;
var marker;

function initialize() {

  var myLatLng = new google.maps.LatLng( <?php echo $firstrow['latitude'].','. $firstrow['longitude'];?> ),
      myOptions = {
      zoom: 16,
      center: myLatLng,
      ......

答案 1 :(得分:0)

将movemarker()更改为:

function moveMarker(){
  setInterval( function(){ 
      $.get("point", function(data){
      var latlng= $.parseJSON(data);
      mymarker.setPosition( new google.maps.LatLng( {latlng} ) );
   });
}, 30000 );

对于&#34;点&#34;页面做:

<?php
     //get last lat and long and send with under code
     echo json_encode($arr);
?>