我試圖實時監控車輛的位置。 我正在使用googlemaps API來執行此操作。 我的目標是每三秒鐘不斷更新標記(我的車的位置),而不必重新加載整個地圖。XMLHttpResponse對象在每次調用時加載相同的內容以打開()
車輛的當前位置保存在'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
「具有在每次調用
req.open("GET", "./vehicle_location.txt", true)
inspite文本文件的不斷變化的值相同。
我是js的新手。任何幫助深表感謝!
那麼其他的手柄是應該更新'vehicle_location.txt'未能這樣做(軟件) 。它也可能是瀏覽器緩存 –
@AdamAzad,該軟件工作正常。 'vehicle_location.txt'文件的內容不斷變化。如果它是瀏覽器緩存,我該如何動態清除它? – sudeepnyk