我想從我的標記(座標等等)從MySQL數據庫中獲取一些數據,然後將這些標記添加到地圖與點擊偵聽器打開infoWindow。谷歌地圖的JavaScript API和MySQL/AJAX
這裏是我的代碼:
// Request to database
function getLocations() {
if (window.XMLHttpRequest) {
var xmlhttp = new XMLHttpRequest();
} else {
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", "getlocations.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var returnValue = JSON.parse(xmlhttp.responseText);
var infoWindow = new google.maps.InfoWindow;
for(var i=0; i<returnValue.length; i++) {
var marker = new google.maps.Marker({
map: map,
icon: icons['ice_green'].icon,
position: new google.maps.LatLng(returnValue[i][2], returnValue[i][3]),
title: '' + returnValue[i][1],
});
marker.addListener('click', function() {
infoWindow.setContent('test');
infoWindow.open(map, marker);
});
}
}
};
xmlhttp.send();
}
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 35.4681174, lng: 5.3043723},
zoom: 17
});
getLocations();
}
到目前爲止,一切正常。標記位於正確的位置,但是當我點擊一個標記時,「infoWindow」僅爲最後添加的標記打開。
有什麼想法?哪裏有問題?
謝謝
你永遠只能創建一個'infoWindow'把這個線'var infoWindow = new google.maps.InfoWindow;''marker.addListener('click',function(){'將會是我的猜測 – George