gpt4 book ai didi

javascript - 将信息窗口添加到多个圆圈叠加层

转载 作者:行者123 更新时间:2023-12-02 18:44:30 26 4
gpt4 key购买 nike

我在向多个圆圈叠加层中的每一个添加信息窗口时遇到问题。当我单击一个圆圈时,会出现一个信息窗口,但不是在我单击的圆圈上,而是在最后添加的圆圈上。似乎每次循环执行时,事件监听器都会添加到每个圆圈中,但信息窗口的内容是从最后添加的圆圈派生的。

for (i in cityPoints) {
var magnitudeOptions = {
map: map,
center: cityPoints[i].center,
radius: cityPoints[i].magnitude,
id:cityPoints[i].id,
addr:cityPoints[i].addr,
infoWindowIndex: i
};
cityCircle = new google.maps.Circle(magnitudeOptions);
circlesArray.push(cityCircle);
infoWindow = new google.maps.InfoWindow({ content: cityPoints[i].id + " " + cityPoints[i].addr });
infoWindowsArray.push(infoWindow);
google.maps.event.addListener(circlesArray[i], 'click', function (ev) {
infoWindowsArray[i].setPosition(cityPoints[i].center);
infoWindowsArray[i].open(map);
});

}

最佳答案

那是因为您传递的 i 参数始终是最后一个。试试这个

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Circles</title>
<style>
#map-canvas {
height: 500px;
width: 500px;
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>

// Create an object containing LatLng, population.
var cityPoints = {};
cityPoints[0] = {
center: new google.maps.LatLng(41.878113, -87.629798),
id: 0,
addr: 'avenue0',
magnitude: 100000
};
cityPoints[1] = {
center: new google.maps.LatLng(40.714352, -74.005973),
id: 1,
addr: 'avenue1',
magnitude: 100000
};
cityPoints[2] = {
center: new google.maps.LatLng(34.052234, -118.243684),
id: 2,
addr: 'avenue2',
magnitude: 100000
}
var cityCircle;
var infoWindow = new google.maps.InfoWindow();

function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(37.09024, -95.712891),
mapTypeId: google.maps.MapTypeId.TERRAIN
};

var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);

for (i in cityPoints) {
var magnitudeOptions = {
map: map,
center: cityPoints[i].center,
radius: cityPoints[i].magnitude,
id:cityPoints[i].id,
addr:cityPoints[i].addr,
infoWindowIndex: i
};
cityCircle = new google.maps.Circle(magnitudeOptions);

google.maps.event.addListener(cityCircle, 'click', (function(cityCircle, i) {
return function() {
infoWindow.setContent(cityPoints[i].id + " " + cityPoints[i].addr);
infoWindow.setPosition(cityCircle.getCenter());
infoWindow.open(map);
}
})(cityCircle, i));
}
}
google.maps.event.addDomListener(window, 'load', initialize);

</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>

关于javascript - 将信息窗口添加到多个圆圈叠加层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16538075/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com