XMLHttpResponse对象在每次调用open()时加载相同的内容

时间:2017-01-02 09:02:53

标签: javascript google-maps

我试图实时监控车辆的位置。 我使用googlemaps API执行此操作。 我的目标是每三秒钟不断更新标记(我的汽车位置),而无需重新加载整个地图。

车辆的当前位置保存在< vehicle_location.txt'中。

<!DOCTYPE html>
    <html>
    <head>
    <title>Car Location</title>
    <style>
    /* Always set the map height explicitly to define the size of the div
     * element that contains the map. */
     #map {
      height: 100%;
     }
    /* Optional: Makes the sample page fill the window. */
    html, body {
    height: 100%;
    margin: 0;
    padding: 0;
    }
    </style>
    </head>
    <body>
    <div id="map"></div>
    <script>
    var map;
    var markers = [];
    var timerId;
    var contents;

    function initMap() {
    ``var initial_location = {lat: 15.3647, lng: 75.1240};
    //timerId = setInterval(update_map,3000);
    update_map();
    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 12,
      center: initial_location,
    });
    addMarker(initial_location);
  }

  // Adds a marker to the map and push to the array.
  function addMarker(location) {
    var marker = new google.maps.Marker({
      position: location,
      map: map
    });
    markers.push(marker);
  }

  // Sets the map on all markers in the array.
  function setMapOnAll(map) {
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(map);
    }
  }

  // Removes the markers from the map, but keeps them in the array.
  function clearMarkers() {
    setMapOnAll(null);
  }

  // Shows any markers currently in the array.
  function showMarkers() {
    setMapOnAll(map);
  }

  // Deletes all markers in the array by removing references to them.
  function deleteMarkers() {
    clearMarkers();
    markers = [];
  }

  //Updates map every 3 seconds
  function update_map(){
    //read_file();
    var req = new XMLHttpRequest();
    req.onreadystatechange = function() 
    {
        if (this.readyState == 4 && this.status == 200) 
        {
            alert(this.responseText);
            timerId = setTimeout('update_map()', 3000);
        }
    };
    //req.addEventListener("load", reqListener);
    req.open("GET", "./vehicle_location.txt", true);
    req.send(null);

  } 

</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?     key=YOUR_APIKEY_HERE&callback=initMap">
</script>

问题是,'this.responseText&#39;每次调用

时都具有相同的值

req.open("GET", "./vehicle_location.txt", true)

尽管文本文件不断变化。

我是js的新手。任何帮助深表感谢!

1 个答案:

答案 0 :(得分:0)

如果软件不断更新vehicle_location.txt而没有任何问题。然后,它可能是浏览器缓存。要覆盖它,最简单的方法是向目标URL添加随机查询,以便浏览器将其标识为新URL;因此,忽略缓存。最常用的是时间戳。

var ts = new Date().getTime(); // output a unix timestamp reflecting the current date and time. 
req.open("GET", "./vehicle_location.txt?t="+ts, true);

上面将生成一个新的URL,每个新的XHR请求发出如下:

./vehicle_location.txt?t=1483349217755
./vehicle_location.txt?t=1483349217757
./vehicle_location.txt?t=1483349217759
./vehicle_location.txt?t=1483349217760