我有这个HTML:
<ul class="google-map__trigger">
<li data-id="marker-1" class="google-map__trigger-item">Trigger Marker 1</li>
<li data-id="marker-2" class="google-map__trigger-item">Trigger Marker 2</li>
</ul>
<div id="google-map" class="google-map"></div>
我有这个JS:
// Infowindow, latitude, longitude
var locations = [
['<div class="google-map__infowindow"><h4>Lervig Brygge</h4><p>Her ligger Lervig Brygge.</p></div>', 58.96746,5.765269],
['<div class="google-map__infowindow"><h4>Regn</h4><p>I denne rundkjøringen regner det. Det regner alltid i denne rundkjøringen. Det er litt av et naturfenomen!</p></div>', 58.96579,5.759518]
];
// Icons are located in this folder
var iconURLPrefix = '/_themes/prototype/graphics/icons/';
// Icons are named
var icons = [
iconURLPrefix + 'location.svg',
iconURLPrefix + 'weather-rain.svg',
]
// Map options
var map = new google.maps.Map(document.getElementById('google-map'),
{
zoom: 16,
center: new google.maps.LatLng(58.966222, 5.762930),
mapTypeControl: false,
streetViewControl: false,
panControl: false,
scrollwheel: false,
navigationControl: false,
scaleControl: false,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_BOTTOM
}
});
var infowindow = new google.maps.InfoWindow({
maxWidth: 200
});
var marker;
var markers = new Array();
var iconCounter = 0;
// Add the markers and infowindows to the map
for (var i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon : icons[iconCounter]
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
iconCounter++;
}
function AutoCenter() {
// Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds();
// Go through each...
$.each(markers, function (index, marker) {
bounds.extend(marker.position);
});
// Fit these bounds to the map
map.fitBounds(bounds);
}
AutoCenter();
如何使用上面的HTML中的列表从Google地图外部触发我的地图标记?我已经看到了解决这个问题的不同方法,但我还没有设法使用我的代码......
感谢任何帮助!
答案 0 :(得分:4)
参考:How to trigger the onclick event of a marker on a Google Maps V3?
//using the index provided by jquery.each()
$('.google-map__trigger-item').each(function(i){
$(this).on('click', function(){
google.maps.event.trigger(markers[i], 'click');
});
});
或者,如果它们没有特定的顺序
//using your id data attribute
$('.google-map__trigger-item').each(function(){
$(this).on('click', function(){
var id = parseInt($(this).data('id').split('-')[1]) -1;
google.maps.event.trigger(markers[id], 'click');
});
});
答案 1 :(得分:1)
像这样(不需要外部库):
<ul class="google-map__trigger">
<li data-id="marker-1" class="google-map__trigger-item">
<a onclick="OpenInfowindowForMarker(1)">Trigger Marker 1</a></li>
function OpenInfowindowForMarker(index) {
google.maps.event.trigger(markers[index], 'click');
}