我在我的html页面上创建了一个带有javascript的谷歌地图,我有多个标记和infowindows。
当用户点击标记时我的信息窗口可见,但我想在页面加载时显示所有信息窗口。
var locations = [
['TRY 620', 36.888932, 30.683421],
['TRY 772', 36.872729, 30.718440],
['TRY 120', 36.870532, 30.640505],
['TRY 32', 36.854875, 30.739554],
['TRY 600', 36.900189, 30.632437]
];
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: searchItemMap
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
}
})(marker, i));
infowindow.open(searchItemMap, marker);
}
答案 0 :(得分:1)
您的代码的一个选项是将标记的唯一信息窗口作为标记的属性附加正确的内容,然后在标记点击监听器中使用this
来引用标记(那么您不会需要功能关闭)。
marker._infowindow = new google.maps.InfoWindow({content: locations[i][0]});
google.maps.event.addListener(marker, 'click', function() {
this._infowindow.open(searchItemMap, this);
});
// open marker on load
google.maps.event.trigger(marker,'click');
代码段
function initialize() {
var searchItemMap = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: searchItemMap
});
bounds.extend(marker.getPosition());
marker._infowindow = new google.maps.InfoWindow({
content: locations[i][0]
});
google.maps.event.addListener(marker, 'click', function() {
this._infowindow.open(searchItemMap, this);
});
// open marker on load
google.maps.event.trigger(marker, 'click');
}
searchItemMap.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initialize);
var locations = [
['TRY 620', 36.888932, 30.683421],
['TRY 772', 36.872729, 30.718440],
['TRY 120', 36.870532, 30.640505],
['TRY 32', 36.854875, 30.739554],
['TRY 600', 36.900189, 30.632437]
];
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>