【发布时间】:2021-06-15 17:39:47
【问题描述】:
我正在尝试在单击特定标记时添加信息窗口。目前,我有 3 个带有不同位置的下拉菜单,因为当它们被选中时,它会在地图上添加一个标记。如何将包含一些内容的信息窗口添加到每个标记?
这是我正在使用的代码
const locationSelect = document.getElementById('location-select');
const markers = [];
const myCoordinates = {
"bigBenCoords" : {
"lat": 51.5007,
"lng": -0.1246},
const infoWindows = [];
const myInfoWindows = {
"bigBenInfo" :
{"content": "Big Ben is a historic landmark in London and has become one of the major and most easily recognisable landmarks of the city. The name 'Big Ben' is the name for the clock in Elizabeth's Tower - the tallest tower in the Palace of Westminster."}
};
function removeMarkers() {
markers.forEach(marker => {
marker.setMap(null); // Disconnect each marker.
});
markers.length = 0; // This empties the array.
}
function createMarker(coordinates, map) {
const marker = new google.maps.Marker({
position: coordinates,
animation: google.maps.Animation.DROP,
map
});
markers.push(marker); // Add the marker to the array to save the reference.
}
function removeInfoWindows() {
infoWindows.forEach(inforWindow => {
infoWindow.setMap(null);
});
infoWindows.length = 0;
}
function addInfoWindow(coordinates, map) {
const infoWindow = new google.maps.InfoWindow({
content: infoWindows,
map
});
infoWindows.push(infoWindow);
}
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: {
lat: 51.509865,
lng: -0.118092
}
});
locationSelect.addEventListener('change', () => {
const location = locationSelect.value;
const coordinates = myCoordinates[location];
const content = myInfoWindows[content];
removeMarkers(); // First remove all markers.
createMarker(coordinates, map); // Then add the marker.
removeInfoWindows();
addInfoWindow(content, map);
});
【问题讨论】:
-
你试过什么?什么不起作用?我什至没有看到在您共享的代码中创建信息窗口的尝试。
-
@MrUpsidown 我已经添加了我之前尝试过的内容
-
您的代码 sn-p 中有语法错误。请提供一个 minimal reproducible example 来证明您的问题。
标签: javascript google-maps google-maps-markers marker infowindow