JS 小提琴:http: //jsfiddle.net/megatimes/NVDLf/7/
我有一个从数组创建多个标记的地图。地图下方是一些链接,单击这些链接时,我想让地图平移到其各自的标记,然后打开信息窗口。
鉴于我不想将链接本身生成为创建标记的循环的一部分,我该怎么做?
我相当确定这是一个范围问题,因为地图下方的链接每个都打开位置数组中的最后一项,但我似乎无法弄清楚如何解决它。
谢谢
var locations = [
[
"Location 1",
"215 West Girard Avenue 19123",
"39.9695601",
"-75.1395161"
],
[
"Location 2",
"5360 Old York Road 19141",
"40.034038",
"-75.145223"
],
[
"Location 3",
"1350 W Girard Avenue 19123",
"39.9713524",
"-75.1590360"
]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(39.9995601, -75.1395161),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
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][2], locations[i][3]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
$(function() {
$('#locations h3 a').each(function() {
$(this).on('click', function() {
google.maps.event.trigger(marker, 'click');
})
});
});
<div id="map" style="width: 500px; height: 400px;"></div>
<div id="locations">
<h3><a href="#">Location 1</a></h3>
<p>Arbitrary content about 1</p>
<h3><a href="#">Location 2</a></h3>
<p>Arbitrary content about 2</p>
<h3><a href="#">Location 3</a></h3>
<p>Arbitrary content about 3</p>
</div>