我今天一直在拼凑这些代码,以显示从我的XML文件中提取的标记。
function load() {
var cluster = [];
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(-36.848461, 174.763336),
zoom: 13,
mapTypeId: 'roadmap'
});
var infowindow = new google.maps.InfoWindow();
downloadUrl('functions/toXml.php', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var price = markers[i].getAttribute("price");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + markers[i].getAttribute("name") + "</b> <br/>" + markers[i].getAttribute("address");
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
marker.addListener('click', (function(marker, i) {
return function() {
infowindow.setContent(html);
infowindow.open(map, marker);
}
})(marker, i));
cluster.push(marker);
}
var mc = new MarkerClusterer(map,cluster,{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
});
}
它主要是工作,但我认为我已经在迭代过程中的某个地方搞砸了,因为我的所有信息窗口都有相同的(最后一个)名称和地址。
我已经移动了一些东西,但无法弄清楚如何解决它。
通过许多迭代和愤怒退出,我已经弄明白了。这是我的代码,以防其他人遇到此问题。
function initMap() {
var cluster = [];
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(-36.848461, 174.763336),
zoom: 12
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP or XML file
downloadUrl('functions/toXml.php', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var name = markerElem.getAttribute('name');
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);
});
cluster.push(marker);
});
var options = {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
};
var mc = new MarkerClusterer(map,cluster,options);
});
};