【发布时间】:2016-09-22 22:39:03
【问题描述】:
我想为谷歌地图上的每个标记创建一个自己的窗口。我试过这个:
// Create first marker and window
marker = new google.maps.Marker({
position: myLatlng,
map: map
});
contentString = '<div>BOX A</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
// Create second marker and window
myLatlng = new google.maps.LatLng(12.1364,-86.2514);
marker = new google.maps.Marker({
position: myLatlng,
map: map
});
contentString = '<div>BOX B</div>';
infowindow = new google.maps.InfoWindow({
content: contentString
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
不幸的是,只有第二个标记有一个包含Box B 的窗口。如果我单击第一个标记,则会弹出带有Box B 的第二个标记的窗口。我不明白为什么会这样。
我注意到,如果我为第二个标记和第二个窗口使用一个新变量,每个标记都有自己的窗口,如下所示:
// Create sceond marker and window
myLatlng = new google.maps.LatLng(12.1364,-86.2514);
marker2 = new google.maps.Marker({
position: myLatlng,
map: map
});
contentString = '<div>BOX B</div>';
infowindow2 = new google.maps.InfoWindow({
content: contentString
});
marker2.addListener('click', function() {
infowindow2.open(map, marker2);
});
但我完全不明白为什么我需要使用新变量。为什么我不能覆盖旧变量?
注意:这个问题是关于如何获取多个不同的 infoWindows,因此不同于 Have just one InfoWindow open in Google Maps API v3 和 Google Maps infoWindow only loading last record on markers
完整代码如下:
<div id="map" style='height:300px'></div>
<script>
function initMap() {
// init map
var mapDiv = document.getElementById('map');
myLatlng = new google.maps.LatLng(52.4955,13.3437);
var map = new google.maps.Map(mapDiv, {
scrollwheel: false,
center: myLatlng,
zoom: 1
});
var myLatlng, marker, infowindow,contentString;
// Create first marker and window
marker = new google.maps.Marker({
position: myLatlng,
map: map
});
contentString = '<div>BOX A</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
// Create second marker and window
myLatlng = new google.maps.LatLng(12.1364,-86.2514);
marker = new google.maps.Marker({
position: myLatlng,
map: map
});
contentString = '<div>BOX B</div>';
infowindow = new google.maps.InfoWindow({
content: contentString
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
</script>
【问题讨论】:
标签: javascript google-maps google-maps-api-3