你可以做的是有一个外部函数来处理标记/信息窗口的添加(参见 150PoundsOfDonamite 的评论)。巧合的是,我今天写了一个blog post,展示了如何做到这一点。
<script type="text/javascript">
function initialize() {
var i;
var arrDestinations = [
{
lat: 50.815155,
lon: -0.137072,
title: "Brighton Pier",
description: "Brighton Palace Pier dates to 1899"
},
{
lat: 50.822638,
lon: -0.137361,
title: "Brighton Pavilion",
description: "The Pavilion was built for the Prince of Wales in 1787"
},
{
lat: 50.821226,
lon: -0.139372,
title: "English's",
description: "English's Seafood Restaurant and Oyster Bar"
}
];
var myOptions = {
zoom: 15,
center: new google.maps.LatLng(50.820645,-0.137376),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var infowindow = new google.maps.InfoWindow({
content: ''
});
// loop over our array
for (i = 0; i < arrDestinations.length; i++) {
// create a marker
var marker = new google.maps.Marker({
title: arrDestinations[i].title,
position: new google.maps.LatLng(arrDestinations[i].lat, arrDestinations[i].lon),
map: map
});
// add an event listener for this marker
bindInfoWindow(marker, map, infowindow, "<p>" + arrDestinations[i].description + "</p>");
}
}
function bindInfoWindow(marker, map, infowindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(html);
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>