对不起标题,不知道该写些什么。
我有一个谷歌地图,我用javascript数组中的标记填充它,标记上有数字,这个数字是用View
函数随机生成的。
到目前为止一切运作良好,标记显示在正确的位置,每个标记上都有一个随机数字。
问题是,当我点击标记时,我正在显示国家/地区的名称及其生成的数字。因此,例如,如果罗马上的标记说" 13"窗口应该说Math.floor()
问题在于随机生成的数字。它总是给我数组中第一个国家/地区的价值,在这个例子中它是"Rome. There are 13 stories in Rome"
。
所以回顾一下,让我们说罗马有13个故事,贝鲁特有45个故事,当我点击罗马的标记时,我得到Beirut
There are 45 stories
答案 0 :(得分:1)
您需要在标记点击事件的函数闭包中包含markernumber。变化:
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0] + '<br>There are ' + markernumber + ' stories.');
infowindow.open(map, marker);
}
})(marker, i));
要:
google.maps.event.addListener(marker, 'click', (function(marker, i, markernumber) {
return function() {
infowindow.setContent(locations[i][0] + '<br>There are ' + markernumber + ' stories.');
infowindow.open(map, marker);
}
})(marker, i, markernumber));
参考问题:Google Maps JS API v3 - Simple Multiple Marker Example(只有标记和i的闭包,因为它就是它所使用的全部)
代码段:
function initialize() {
var map = 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 locations = [
['Italy 3', 45.343294, 8.853324, 16],
['Italy 2', 44.534529, 10.303519, 15],
['Italy 1', 41.416810, 15.313285, 14],
['Bulgaria', 42.235462, 23.838675, 13],
['Albania', 41.317868, 20.147269, 12],
['Turkey 2', 39.714402, 32.803519, 11],
['Turkey 1', 37.968918, 29.200003, 10],
['Romania 2', 44.251917, 25.464652, 9],
['Romania 1', 45.651325, 22.476371, 8],
['Bosnia', 43.872979, 17.246879, 7],
['Serbia', 43.841292, 20.718558, 6],
['Athens', 37.977984, 23.741343, 4],
['Istanbul', 41.2440257, 29.0616179, 5],
['Rome', 41.851999, 12.555716, 3],
['Berlin', 52.481801, 13.291800, 2],
['Beirut', 33.787747, 35.796924, 1]
];
var infowindow = new google.maps.InfoWindow();
var marker, i;
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
var markernumber = Math.floor((Math.random() * 100) + 1);
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=' + markernumber + '|F6DD0E|000000'
});
google.maps.event.addListener(marker, 'click', (function(marker, i, markernumber) {
return function() {
infowindow.setContent(locations[i][0] + '<br>There are ' + markernumber + ' stories.');
infowindow.open(map, marker);
}
})(marker, i, markernumber));
bounds.extend(marker.getPosition());
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initialize);
&#13;
html,
body,
#map_canvas {
height: 500px;
width: 500px;
margin: 0px;
padding: 0px
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas" style="border: 2px solid #3872ac;"></div>
&#13;