2017-05-11 74 views
-1

我是新的谷歌地图,所以我想你的帮助,我想要做的是更新地图与新位置而不刷新页面,我使用ajax从终点获取位置这些位置自动更新,但当我去我的网站时,我必须刷新它才能看到新的位置我不知道为什么它不起作用,有没有解决方法,这里是我的代码如何更新谷歌地图上的标记而不刷新

var map; 
 

 
function initMap() { 
 
    var uluru = {lat: 29.91, lng: 31.21}; 
 
    map = new google.maps.Map(document.getElementById('map'), { 
 
    zoom: 6, 
 
    center: uluru 
 
    }); 
 

 

 
    // AJAX call to retrieve data from website 
 
    function getinformation() { 
 
    var xhttp; 
 
    xhttp = new XMLHttpRequest(); 
 
    xhttp.onreadystatechange = function() { 
 
     if (xhttp.readyState == 4 && xhttp.status == 200) { 
 
      var result = xhttp.responseText, // response in order to be repeated 
 
       data = JSON.parse(result); // converting recieved JSON into array of objects 
 

 
       console.log(data); 
 

 
       var markers = []; 
 
        contents = [], 
 
        infowindows = []; 
 

 
         for (i = 0; i < data.length; i++) { 
 
          markers[i] = new google.maps.Marker({ 
 
           position: {lat: data[i].lat, lng:data[i].long}, // modified to recieve all info even status 
 
           map: map, 
 
           animation: google.maps.Animation.BOUNCE 
 
          }); 
 

 
          
 
          markers[i].index = i; 
 
          contents[i] = '<div class="popup_container" style="padding: 5px">' + data[i].status +'</div>'; 
 

 
          console.log(markers); 
 
          infowindows[i] = new google.maps.InfoWindow({ 
 
          content: contents[i], 
 
          maxWidth: 300 
 
          }); 
 

 
          google.maps.event.addListener(markers[i], 'click', function() { 
 
            console.log(this.index); // this will give correct index 
 
            console.log(i); //this will always give 10 for you 
 
            infowindows[this.index].open(map,markers[this.index]); 
 
            map.panTo(markers[this.index].getPosition()); 
 
          }); 
 
         } 
 

 
      } 
 
    }; 
 
    xhttp.open("GET", 'api/v1/record/all', true); 
 
    xhttp.send(); 
 
    } 
 
    getinformation(); 
 
}

谢谢

回答

0

为什么您需要刷新页面,只需清除地图并重新定位标记 map.clear()您可以使用然后重新定位标记在地图上的位置,在那里获取新位置。

希望它会帮助!

+0

thanx为你的帮助,但如果你不介意可以ü请修改我的代码,因为我从这个新的api困惑 –