它们是 2 个独立的实体 atm:
https://jsfiddle.net/31b2tbpu/13/
我希望链接它们,因此单击列表项会使该框出现在相应的 map 项上,单击 map 项会更改列表项的颜色等。
我是否需要每个 anchor 来调用一个改变的函数:
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
最佳答案
保留一个标记数组,以便您可以通过索引访问它们
var gmarkers = [];
在实例化标记时将其推送到该数组上。
添加代码,以便在单击
li
元素时在相应标记上click
:
$('#list li').each(function(i, e) {
$(e).click(function(i) {
return function(e) {
google.maps.event.trigger(gmarkers[i], 'click');
}
}(i));
});
请注意,此代码假定位置数组和列表项的顺序相同。您可以使用名称或 ID 来代替该假设。
代码片段:
// Locations: [title, lat, long, number]
var locations = [
['Bar Termini', 51.51367, -0.12981, 1],
['French House', 51.51272, -0.13170, 2],
['Mark\'s Bar', 51.51133, -0.13563, 3],
['Hakkasan (bar)', 51.51017, -0.14474, 4],
['Bar Américain at Brasserie Zédel', 51.51017, -0.14474, 5],
['Experimental Cocktail Club', 51.51193, -0.13103, 6],
['Milk & Honey', 51.51377, -0.13653, 7],
['Blind Pig', 51.51379, -0.13668, 8],
['Opium', 51.51176, -0.13145, 9]
];
var gmarkers = [];
// Map Settings
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 16,
center: new google.maps.LatLng(51.51367, -0.12981),
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][1], locations[i][2]),
map: map,
label: String(locations[i][3])
});
gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
$('#list li').each(function(i, e) {
$(e).click(function(i) {
return function(e) {
google.maps.event.trigger(gmarkers[i], 'click');
}
}(i));
});
#map {
height: 400px;
width: 100%;
}
a {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.google.com/maps/api/js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div data-role="page" id="map_result">
<div data-role="header" data-position="fixed">
<h1>Multiple Marker</h1>
</div>
<div data-role="content" style="padding:0;">
<div id="map"></div>
<div id="list">
<ol>
<li>
<a>Bar Termini</a>
</li>
<li>
<a>French House</a>
</li>
<li>
<a>Mark's Bar</a>
</li>
<li>
<a>Hakkasan (bar)</a>
</li>
<li>
<a>Bar Americain at Brasserie Zedel</a>
</li>
<li>
<a>Experimental Cocktail Club</a>
</li>
<li>
<a>Milk & Honey</a>
</li>
<li>
<a>Blind Pig</a>
</li>
<li>
<a>Opium</a>
</li>
</ol>
</div>
</div>
</div>
关于javascript - 如何将地点列表与 Google map 点连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35182728/