2016-11-03 1 views
3

"에서 동적으로 Google지도의 자동 마커 위치 자동 업데이트"작업 중입니다. 내가 페이지를 새로 고칠 때, 그 시간 마커는 자동으로 업데이트됩니다. 하지만 내가 새로운 위치 (lat, lng)를 데이터베이스에 삽입 할 때마다 Google지도에서 마커 위치를 업데이트하려고합니다. 라이브 추적 시스템과 같습니다.새로운 마커 위치가 데이터베이스에 삽입되었을 때 Google지도에서 여러 마커 위치를 업데이트하십시오.

스크립트 :이 JSFiddle 링크를 따랐다

<?php 
include('header.php'); 

$query = $this->db->query("SELECT m.*, d.name FROM `map` as m LEFT JOIN device as d ON d.id = m.device_id WHERE m.id IN (SELECT MAX(id) FROM `map` GROUP BY device_id);"); 
$result = $query->result(); 

?> 

<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyAbaTTWnkEvs_H4uKBDv_-OLN_wMYxjx0M" type="text/javascript"></script> 

<!--main content start--> 
<section id="main-content"> 
    <section class="wrapper"> 
     <!-- page start--> 
     <div class="row"> 
      <div class="col-lg-12"> 
       <!--breadcrumbs start --> 
       <ul class="breadcrumb"> 
        <li class="active"><a href=""><i class="fa fa-home"></i> Home</a></li> 
       </ul> 
       <!--breadcrumbs end --> 
      </div> 
     </div> 
     <div class="row"> 
      <div class="col-lg-12"> 
       <section class="panel"> 
        <header class="panel-heading"> Timeline <span class="tools pull-right"></span></header> 
        <div class="panel-body profile-activity"> 

         <div id="map_2385853" style="width: 100%; height: 655px;"></div> 

         <input type="button" value="Reload markers" id="reloadMarkers" class="form-control"> 

        </div> 
       </section> 
      </div> 
     </div> 
     <!-- page end--> 
    </section> 
</section> 
<!--main content end--> 

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script> 
<script language="javascript" type="text/javascript"> 

    var map = new google.maps.Map(document.getElementById('map_2385853'), { 
     zoom: 5, 
     maxZoom: 8, 
     minZoom: 1, 
     streetViewControl: false, 
     center: new google.maps.LatLng(20.5937, 78.9629), 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    }); 

    //initial dataset for markers 
    var locs = { 

     1: { info:'Demo', lat:31.933517, lng:74.910278 }, 
     2: { info:'Demo', lat:32.073266 , lng:76.997681 }, 
     3: { info:'Demo', lat:32.23139 , lng:78.425903 }, 

    }; 

    var locations = {};//A repository for markers (and the data from which they were contructed). 

    var infowindow = new google.maps.InfoWindow(); 

    var auto_remove = true;//When true, markers for all unreported locs will be removed. 

    function setMarkers(locObj) { 
     if(auto_remove) { 
      //Remove markers for all unreported locs, and the corrsponding locations entry. 
      $.each(locations, function(key) { 
       if(!locObj[key]) { 
        if(locations[key].marker) { 
         locations[key].marker.setMap(null); 
        } 
        delete locations[key]; 
       } 
      }); 
     } 

     $.each(locObj, function(key, loc) { 
      if(!locations[key] && loc.lat!==undefined && loc.lng!==undefined) { 
       //Marker has not yet been made (and there's enough data to create one). 

       //Create marker 
       loc.marker = new google.maps.Marker({ 
        position: new google.maps.LatLng(loc.lat, loc.lng), 
        map: map 
       }); 

       //Attach click listener to marker 
       google.maps.event.addListener(loc.marker, 'click', (function(key) { 
        return function() { 
         if(locations[key]) { 
          infowindow.setContent(locations[key].info); 
          infowindow.open(map, locations[key].marker); 
         } 
        } 
       })(key)); 

       //Remember loc in the `locations` so its info can be displayed and so its marker can be deleted. 
       locations[key] = loc; 
      } 
      else if(locations[key] && loc.remove) { 
       //Remove marker from map 
       if(locations[key].marker) { 
        locations[key].marker.setMap(null); 
       } 
       //Remove element from `locations` 
       delete locations[key]; 
      } 
      else if(locations[key]) { 

        //Update the previous data object with the latest data. 
        $.extend(locations[key], loc); 
        if(loc.lat!==undefined && loc.lng!==undefined) { 
         //Update marker position (maybe not necessary but doesn't hurt). 
          locations[key].marker.setPosition(
           new google.maps.LatLng(loc.lat, loc.lng) 
          ); 
        } 
        //locations[key].info looks after itself. 
      } 
     }); 
    } 

    var ajaxObj = {//Object to save cluttering the namespace. 
     options: { 
      url: "<?php echo base_url().'index.php/home/index'; ?>",//The resource that delivers loc data. 
      dataType: "json"//The type of data tp be returned by the server. 
     }, 
     delay: 10000,//(milliseconds) the interval between successive gets. 
     errorCount: 0,//running total of ajax errors. 
     errorThreshold: 5,//the number of ajax errors beyond which the get cycle should cease. 
     ticker: null,//setTimeout reference - allows the get cycle to be cancelled with clearTimeout(ajaxObj.ticker); 
     get: function() { //a function which initiates 
      if(ajaxObj.errorCount < ajaxObj.errorThreshold) { 
       ajaxObj.ticker = setTimeout(getMarkerData, ajaxObj.delay); 
      } 
     }, 
     fail: function(jqXHR, textStatus, errorThrown) { 
      console.log(errorThrown); 
      ajaxObj.errorCount++; 
     } 
    }; 

    //Ajax master routine 
    function getMarkerData() { 
     $.ajax(ajaxObj.options) 
      .done(setMarkers) //fires when ajax returns successfully 
      .fail(ajaxObj.fail) //fires when an ajax error occurs 
      .always(ajaxObj.get); //fires after ajax success or ajax error 
    } 

    setMarkers(locs);//Create markers from the initial dataset served with the document. 
    //ajaxObj.get();//Start the get cycle. 

    function myTimer() { 

     var testLocs = { 

      <?php $count = 1; if(empty($result)){ } else { 
      foreach ($result as $map){ ?> 
      <?php echo $count++; ?>: { info:'<?php echo $map->name; ?>', lat:<?php echo $map->latitude; ?>, lng:<?php echo $map->longitude; ?> }, 
      <?php } } ?> 
     }; 

     setMarkers(testLocs); 
    } 
    var myVar = setInterval(function(){ myTimer() }, 3000); 

</script> 

<?php include('footer.php'); ?> 

편집. ... 코드와 JSFiddle

답변

2

제거 VAR 아약스는이 당신이() 에코로 json_encode ($ 배열) (아약스 호출) 배열의 JSON을 반환 컨트롤러 확인

window.setInterval(function(){ 
     getnewmarker(); /// call your function here 
}, 5000); 


// Ajex call wchich set updated data 
function getnewmarker() 
{ 
    var url = "<?php echo site_url('index.php/home/index'); ?>"; // your url 

    $.ajax({ 
      url: url, 
      type: 'post', 
      data: {}, 
      dataType : 'json', 
      success: function(data) { 

       locs = data; 
       setMarkers(locs); 

      }, 

     });// end ajax call 
} 

이하로 사용하는 구조

같은
$array = array(
      '1' => array("info"=>'Demo', "lat"=>31.933517, "lng"=>74.910278), 
      '2' => array("info"=>'Demo', "lat"=>32.073266 , "lng"=>76.997681), 
      '3' => array("info"=>'Demo', "lat"=>32.23139 , "lng"=>78.425903), 
    ); 
관련 문제