Здравствуйте!
Есть у меня карта, которая должна получать с сервера маркеры и показывать их на экран. Т.к. позиции маркеров меняются каждую минуту, то необходимо создать прорисовку маркеров без перезагрузки страницы.
Все "работает", но:
1. В хроме и подобных ему браузерах POST-запрос кешируется браузером (маркеры не меняют свою локацию)
2. Во всех браузерах постепенно карта заливается белым цветом, и через минут 5 видны только маркеры на белом фоне.
Код:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&extn=.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.1.1.min.js"></script>
<script>
$( document ).ready(function() {
var locations = {};
var latitude = 40.000000,
longitude = 30.000000,
radius = 8000,
center = new google.maps.LatLng(latitude,longitude),
bounds = new google.maps.Circle({center: center, radius: radius}).getBounds(),
mapOptions = {
center: center,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: true,
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var infowindow = new google.maps.InfoWindow();
var auto_remove = true;//When true, markers for all unreported locs will be removed.
function setMarkers(locObj) {
console.log('STM');
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) {
loc.marker = new google.maps.Marker({
position: new google.maps.LatLng(loc.lat, loc.lng),
map: map
});
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));
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: "/map.php",//The resource that delivers loc data.
dataType: "json"//The type of data tp be returned by the server.
},
delay:4000,//(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
}
setInterval(function() {
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "/map.php",
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
var circle = new google.maps.Circle({
strokeColor: '#000000',
strokeOpacity: 0.25,
strokeWeight: 1.0,
fillColor: '#ffffff',
fillOpacity: 0.1,
clickable: false,
map: map,
center: center,
radius: radius
});
console.log('logg' + json);
setMarkers(json);
}, 10000);
});
</script>
</head>
<body>
<div id="map-canvas" ></div>
</body>
</html>
maps.php Отдает примерно следующее:
[{"lat":41.000000,"lng":31.000000,"info":"test1"},{"lat":42.000000,"lng":32.000000,"info":"test2"}]