我一直在使用谷歌地图,并希望在我点击地图外的元素时以标记为中心并打开相应的infoWindow。 例如我有;
<div id="map"></div>
Store A
Opening Hours: 10-10
Store B
Opening Hours: 10-4
Store C
Opening Hours: 9-9
Store D.
Opening Hours: 8-9
我希望它可以工作,当我点击列表中的一个商店(地图外)时,它会调用相应的标记,以它为中心并打开附加的infoWindow。 infoWindow正在处理标记点击。
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: {
lat: -33.800426,
lng: 142.038494
}
});
setMarkers(map);
}
// Data for the markers consisting of a name, a LatLng and a zIndex for the
// order in which these markers should display on top of each other.
var stores = [
['A', -33.771624, 142.888128, 1],
['B', -33.843956, 142.994875, 2],
['C', -33.818086, 142.995699, 3],
['C', -33.812697, 143.229200, 4],
];
function setMarkers(map) {
// Adds markers to the map.
for (var i = 0; i < stores.length; ++i) {
var store = stores[i];
const marker = new google.maps.Marker({
position: {
lat: store[1],
lng: store[2]
},
map: map,
animation: google.maps.Animation.DROP,
title: store[0],
zIndex: store[3],
});
attachStoreTitle(marker);
}
}
// Attaches an info window to a marker with the provided message. When the
// marker is clicked, the info window will open with message.
function attachStoreTitle(marker) {
var infowindow = new google.maps.InfoWindow({
content: marker.title
});
marker.addListener('click', function() {
infowindow.open(marker.get('map'), marker);
});
}
initMap()
答案 0 :(得分:0)
如果我已经理解了你的要求,我认为你应该能够做到这一点:
marker.addListener('click', function() {
infowindow.open(marker.get('map'), marker);
marker.get('map').setCenter(this.getPosition());
});
答案 1 :(得分:0)
https://jsfiddle.net/00e58pba/8/
完成小提琴将事件监听器附加到标记,然后打开正确的infoWindow -
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
// Close all other infoboxes
for (var j = 0; j < markers.length; j++) {
markers[j].infobox.close(map);
}
// Open correct info box
markers[i].infobox.open(map, markers[i]);
}
})(marker, i));