我试图用内容显示多个标记。 这是我正在使用的代码 -
var latitude=[10,20,30];
var longitude=[10,20,30];
var address=["Test1","Test2","Test3"];
function initialize() {
var mapObject = {
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"), mapObject);
loadMarkers();
}
google.maps.event.addDomListener(window, 'load', initialize);
function loadMarkers() {
for (var i = 1; i < latitude.length; i++) {
var markerCenter = new google.maps.LatLng(latitude[i], longitude[i]);
var marker = new google.maps.Marker({
position: markerCenter,
animation: google.maps.Animation.BOUNCE
});
marker.setMap(map);
marker.info = new google.maps.InfoWindow({
content: address[i]
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function () {
marker.info.open(map, marker);
});
}
}
问题在于它始终显示地址数组的最后一个地址。 有人可以帮帮我吗?
答案 0 :(得分:1)
您的代码中缺少一些内容。就像地图的起始缩放和中心一样。
但事情是这样的: - 制作1个infowindow,并一次又一次地使用它。 - 我看到你有markers.push(marker);在你的代码中。这很好(也许你看到我的其他帖子之一)。当你有这个(标记对象)数组时,你可以看到点击了哪个标记
我认为这就是你想要的。
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
var latitude=[10, 20, 30];
var longitude=[10, 20, 30];
var address=["Test1", "Test2", "Test3"];
var markers = []; // store the marker objects here
var infoWindow;
function initialize() {
var mapObject = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 4,
center: new google.maps.LatLng(latitude[1], longitude[1]) // let's take the middle marker as center
};
map = new google.maps.Map(document.getElementById("googleMap"), mapObject);
loadMarkers();
}
google.maps.event.addDomListener(window, 'load', initialize);
function loadMarkers() {
for (var i=0; i<=latitude.length; i++) {
var markerCenter = new google.maps.LatLng(latitude[i], longitude[i]);
var marker = new google.maps.Marker({
position: markerCenter,
// animation: google.maps.Animation.BOUNCE,
map: map // replaces marker.setMap(map);
});
markers.push(marker); // store the marker in the array
// click on the marker
google.maps.event.addListener(marker, 'click', function () {
// first we want to know which marker the client clicked on.
var i=markers.indexOf(this);
// we set the content of infoWindow, then we open it.
infoWindow.setContent(address[i])
infoWindow.open(map, markers[i]);
});
}
// make 1 infowindow. We will use it again and again
infoWindow = new google.maps.InfoWindow({
content: ''
});
}
</script>
<style>
#googleMap {
height: 400px;
}
</style>
<div id="googleMap"></div>