实时更新Google地图标记,无需刷新整个地图
问题描述:
我一直在关注Google网站上关于如何正确实施Google地图和MySQL数据的教程。一切正常,但在地图上获取最新标记的唯一方法是刷新页面。我试图将SetInterval添加到整个函数中,它可以工作。但是,每次循环时,整个地图都会刷新。如果您在地图上移动,然后重置在地图上,这尤其令人讨厌。有没有什么办法可以使标记刷新?按照我的理解,最新的数据必须在每次循环中从MySQL中取出。这里是我的代码:实时更新Google地图标记,无需刷新整个地图
<div class="container">
<h3>Location of Devices</h3>
<div id="map">
</div>
</div>
<script>
var customLabel = {
restaurant: {
label: 'R'
},
bar: {
label: 'B'
}
};
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(XX.XXXX, XX.XXXX),
zoom: 17
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP or XML file
downloadUrl('http://XXXXX.com/XXXXXXX.php/', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var id = markerElem.getAttribute('id');
var name = markerElem.getAttribute('id');
var address = markerElem.getAttribute('address');
var type = markerElem.getAttribute('type');
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customLabel[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
label: icon.label
});
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
infoWindow.open(map, marker);
});
});
})
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
我试着添加setInterval()到initMap()和downloadUrl()。我不想将Interval添加到initMap(),除非有办法使代码不会一遍又一遍刷新整个地图。有什么办法可以做到这一点?
答
这里是我的建议:
- 创建一个名为一个全局变量,并在
initMap
函数初始化。 - 每当位置改变时使用
marker.setPosition(new google.maps.LatLng(/*put the lat*/,/*put the lng*/))
函数将标记设置为新的位置。
通过这种方式,你不会一遍又一遍地重新创建标记。
希望有所帮助!
更新标记:1.删除现有标记,2.再次调用downloadUrl。如果你需要做很多事情,并且标记是“移动”的,你可以(而不是删除所有标记),将每个标记移动到它的新位置(在downloadUrl的回调函数中) – geocodezip
相关问题:[ Google地图V3:更新标记](https://stackoverflow.com/questions/20498760/google-maps-v3-updating-markers) – geocodezip
请注意,您可能也有缓存方面的问题,很难分辨所发布的信息。 – geocodezip