我一直在玩谷歌地圖API添加多個標記和樣式。我有這一切工作正常,但我無法工作的是每個標記的InfoWindow。我設法讓InfoWindow工作一點,但它只顯示所有標記的第一個位置/地址。Google Maps API InfoWindow只顯示所有標記的第一個位置
請注意,地址/位置將使用CMS系統添加,並且不會手動添加。
下面是我一直在努力與代碼:
$(document).ready(function() {
var map;
var elevator;
var myOptions = {
zoom: 3,
center: new google.maps.LatLng(50, -30),
mapTypeId: 'terrain'
};
map = new google.maps.Map($('#map_canvas')[0], myOptions);
var styles = [{"featureType":"water","stylers":[{"color":"#46bcec"},{"visibility":"on"}]},{"featureType":"landscape","stylers":[{"color":"#f2f2f2"}]},{"featureType":"road","stylers":[{"saturation":-100},{"lightness":45}]},{"featureType":"road.highway","stylers":[{"visibility":"simplified"}]},{"featureType":"road.arterial","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"administrative","elementType":"labels.text.fill","stylers":[{"color":"#444444"}]},{"featureType":"transit","stylers":[{"visibility":"off"}]},{"featureType":"poi","stylers":[{"visibility":"off"}]}];
map.setOptions({styles: styles});
var addresses = [ '10007','75008','28008','21465','SE91AA',];
for (var x = 0; x < addresses.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
var pinColor = "academia.png";
var pinImage = new google.maps.MarkerImage("/assets/images/pin-green.png",
new google.maps.Size(22, 31));
var contentString = '<div>'+ addresses[0] +'</div>';
var marker = new google.maps.Marker({
position: latlng,
map: map,
clickable: true,
icon: pinImage,
title: addresses[0],
});
google.maps.event.addListener(marker, 'click', getInfoCallback(map, contentString));
});
}
function getInfoCallback(map, content) {
var infowindow = new google.maps.InfoWindow({content: content});
return function() {
infowindow.setContent(content);
infowindow.open(map, this);
};
}
}
感謝您的幫助@wooer完美地工作。 – Adam
我很高興我的幫助。快樂編碼:) – wooer