douhutongvm382381 2014-10-06 20:12
浏览 37
已采纳

自动更新标记谷歌地图v3

Good afternoon, I created a map that fills markers with coordinates directly from my mysql database, the map is being generated correctly and markers work when I load the page. Every minute I get new coordinates in the bank and want to update the map with a time interval. For this I used the setInterval that calls the initialization function of the markers, however, are not creating new markers on the map, is always displaying the same, they only update when I give f5 on the page, ie if reloading the page works, but with no interval. He even winked on the map when the time set by the interval, but not updated.

My code:

    <script src="js/markerclusterer.js"></script>
<script src="js/jquery-1.5.2.min.js"></script>
<script src="js/jquery.maskedinput-1.3.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
 <?php
     if($attmap_form > 0) {
         echo 'myTimer = window.setInterval(refreshMapa,"'.$attmap_form.'");';
     }
 ?>
 function initialize() {
    var mapOptions = {
        zoom: 12,
        center: new google.maps.LatLng(-25.4848801,-49.2918938),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    locations = [];
    <?php
        require('conecta.php');
        $sql_lista = ("SELECT MONITLATITUDE,MONITLONGITUDE,MONITDATA,MONITHORA,MONITRAIO,MONITPROVEDOR,MONITVELOCIDADE FROM MONITORAMENTO where MONITHORA BETWEEN '$hora1_form' AND '$hora2_form' AND MONITDATA BETWEEN '$data1_form' AND '$data2_form' AND EQUIPIMEI = $imei");
        $query_lista  = mysql_query($sql_lista);
        $achados_lista = mysql_num_rows($query_lista);
        while ($achados_lista = mysql_fetch_array($query_lista)) {
            $lat = $achados_lista['MONITLATITUDE'];
            $lon = $achados_lista['MONITLONGITUDE'];
            $Data = $achados_lista['MONITDATA'];
            $hora = $achados_lista['MONITHORA'];
            $raio = $achados_lista['MONITRAIO'];
            $provedor = $achados_lista['MONITPROVEDOR'];
            $velocidade = $achados_lista['MONITVELOCIDADE'];
            echo 'locations.push ( {Data:"'.$Data.'", latlng: new google.maps.LatLng('.$lat.', '.$lon.'), hora:"'.$hora.'", raio:"'.$raio.'",provedor:"'.$provedor.'",velocidade:"'.$velocidade.'"} );';
        }
    ?>
    var bounds = new google.maps.LatLngBounds();
    var infowindow = new google.maps.InfoWindow();
    var markers = [];
    for(var i=0;i < locations.length;i++ ) {
        var marker = new google.maps.Marker({
            position: locations[i].latlng,
            map:map,
            title:locations[i].hora
        });
        markers.push(marker);
        bounds.extend(locations[i].latlng);
        google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
              infowindow.setContent(
                 '<strong>Data: ' + locations[i].Data + '<br>Hora: ' + locations[i].hora + '<br></strong>Velocidade aproximada: ' + locations[i].velocidade + ' K/H<br>Raio aproximado de: ' + locations[i].raio + ' metros <br>Provedor: ' + locations[i].provedor + '<br>Latitude: ' + locations[i].latlng
              );
              infowindow.open(map, marker);
            }
       })(marker, i));
    }
    markerClusterer = new MarkerClusterer(map, markers, {
      maxZoom: 16,
      gridSize: 60
    });
    map.fitBounds(bounds);
}
arrancaMapa();
function arrancaMapa() {
   google.maps.event.addDomListener(window, 'load', initialize);
}
function refreshMapa() {
   initialize();
   arrancaMapa();
}
function clearMarkers() {
     setAllMap(null);
}
function stopTimer() {
    $("#campoAttMap").val("0");
    clearInterval(myTimer);
}
 </script>
  • 写回答

3条回答 默认 最新

  • duanrongpai9556 2014-10-06 20:26
    关注

    You shouldn't have to call initialize more than once. You should implement a different logic, for example get the newest marker that is not in the map and add it via

    var marker = new google.maps.Marker({
            position: locations[i].latlng,
            map:map,
            title:locations[i].hora
        });
        markers.push(marker);
        bounds.extend(locations[i].latlng);
        google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
              infowindow.setContent(
                 '<strong>Data: ' + locations[i].Data + '<br>Hora: ' + locations[i].hora + '<br></strong>Velocidade aproximada: ' + locations[i].velocidade + ' K/H<br>Raio aproximado de: ' + locations[i].raio + ' metros <br>Provedor: ' + locations[i].provedor + '<br>Latitude: ' + locations[i].latlng
              );
              infowindow.open(map, marker);
            }
       })(marker, i));
    

    UPDATE:

    I will add take the following approach. I don't like mixing PHP and Javascript together, I prefer using JSON and AJAX request.

    Update your functions to look like this:

    var map;
    var markers = [];
    
    setInterval(refreshMapa, 3000);
    
    function initialize() {
      var mapOptions = {
          zoom: 12,
          center: new google.maps.LatLng(-25.4848801,-49.2918938),
          mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
      var locations = [];
    
      $.get("getmarkers.php", function(response){
        for(var i = 0; i < response.markers.length; i++) {
          var marker = response.markers[i];
          var myMarker = {
            Data: marker.Data,
            latlng: new google.maps.LatLng(marker.lat, marker.lon),
            hora: marker.hora,
            raio: marker.raio,
            provedor: marker.provedor,
            velocidade: marker.velocidade
          };
    
          locations.push(myMarker);
          addMapMarker(myMarker);
        }
      },'json');
    
      markerClusterer = new MarkerClusterer(map, markers, {
        maxZoom: 16,
        gridSize: 60
      });
      map.fitBounds(bounds);
    }
    
    function refreshMapa() {
    // make sure this one only returns markers that are new and not in the map
    $.get("getnewmarkers.php", function(){
     for(var i = 0; i < response.markers.length; i++) {
       var marker = response.markers[i];
       var myMarker = {
         Data: marker.Data,
         latlng: new google.maps.LatLng(marker.lat, marker.lon),
         hora: marker.hora,
         raio: marker.raio,
         provedor: marker.provedor,
         velocidade: marker.velocidade
       };
    
       locations.push(myMarker);
       addMapMarker(myMarker);
     }, 'json');
    }
    
    function addMapMarker(myMarker) {
       var marker = new google.maps.Marker({
          position: myMarker.latlng,
          map:map,
          title:myMarker.hora
        });
        markers.push(marker);
        bounds.extend(myMarker.latlng);
        google.maps.event.addListener(marker, 'click', (function(marker, i) {
          return function() {
            infowindow.setContent('<strong>Data: ' + myMarker.Data + '<br>Hora: ' + myMarker.hora + '<br></strong>Velocidade aproximada: ' + myMarker.velocidade + ' K/H<br>Raio aproximado de: ' + myMarker.raio + ' metros <br>Provedor: ' + myMarker.provedor + '<br>Latitude: ' + myMarker.latlng);
            infowindow.open(map, marker);
          }
        })(marker, i));
    }
    

    PS: I'm not sure if the implementation of the addMapMarker is correct I just assumed you had it right in the first place, you should check the documentation and make sure it is correct.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?