我正在努力解决这个看似简单的问题。我想在Google地图中为多个标记添加弹出消息。以下是我目前稍微简化的代码:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Map1</title>
<style type="text/css">
html, body, #map-canvas {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
#marker-tooltip {
display: none;
position:absolute;
width: 300px;
height: 200px;
background-color: #ccc;
margin: 15px;
}
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(52.04, -1.5),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var pinString1 = '{"lat":52.04,"lng":-1.5}';
var pinString2 = '{"lat":52.21,"lng":-1.22}';
var infowindow = new google.maps.InfoWindow({
content: "Pin1 Popup"
});
var marker = new google.maps.Marker({
position: JSON.parse(pinString1),
map: map,
title: 'Pin1 Title'
});
marker.addListener('click', function () {
infowindow.open(map, marker);
});
infowindow = new google.maps.InfoWindow({
content: "Pin2 Popup"
});
marker = new google.maps.Marker({
position: JSON.parse(pinString2),
map: map,
title: 'Pin2 Title'
});
marker.addListener('click', function () {
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
似乎点击事件仅添加到最后一个标记。为什么会这样?我该如何解决这个问题?
PS:
将此重构为函数也解决了使用标记两次的问题:
function CreateMarker(markerPositionString, markerTitle, infoWindowContent, map) {
var infowindow = new google.maps.InfoWindow({
content: infoWindowContent
});
var marker = new google.maps.Marker({
position: JSON.parse(markerPositionString),
map: map,
title: markerTitle
});
marker.addListener('click', function () {
infowindow.open(map, marker);
});
}
答案 0 :(得分:1)
您对两个不同的标记对象使用相同的引用。您应该为每个标记创建单独的引用:
// create first reference
var marker1 = new google.maps.Marker({
position: JSON.parse(pinString1),
map: map,
title: 'Pin1 Title'
});
marker1.addListener('click', function () {
infowindow.open(map, marker1);
});
// ...
// create second reference
var marker2 = new google.maps.Marker({
position: JSON.parse(pinString2),
map: map,
title: 'Pin2 Title'
});
marker2.addListener('click', function () {
infowindow.open(map, marker2);
});