使用按钮在地图上显示相关的位置地图标记



我刚刚开始使用JavaScript,正在使用Google Maps API。我想使用按钮在地图上显示位置。我有不同的城堡,当单击每个城堡时,我希望弹出与城堡相关的地图标记。我不确定使用javascript执行此操作的最佳方法。任何帮助不胜感激!我目前在一个数组中拥有城堡的所有位置,并且有一些javascript,尽管它没有显示任何内容。

for (i = 0; i < castles.length; i++ ) {
var addMarker = ("The lat is " + castles[i][1]+" and the long is "+ castles[i][2]);
var marker = new google.maps.Marker({
position: {lat: castles[1], lng: castles[2]},
map: map
});
}

好吧,所以听起来你有一个城堡对象数组,但没有一个标记数组,所以让我们先解决这个问题。(请注意,在您的示例中,您没有访问 lat/lng 的数组[i]中的正确元素。

const markers = [];
for (let i = 0; i < castles.length; i++ ) {
var marker = new google.maps.Marker({
position: { lat: castles[i][1], lng: castles[i][2] },
map: map
});
markers.push(marker);
}

我已经声明了一个新数组来保留所有标记,并在每次迭代时将每个创建的标记推送到其中。

要将这些添加到地图中,只需迭代标记数组并使用setMap

markers.forEach((marker) => marker.setMap(map));

但是,当您单击任何标记时,您还希望出现一个信息窗口,因此让我们返回并修改该循环:

const markers = [];
for (let i = 0; i < castles.length; i++ ) {
// Cache the lat and lng coords
const lat = castles[i][1];
const lng = castles[i][2];
// Create a new infowindow
const infowindow = new google.maps.InfoWindow({
// Using your content we can create a template literal string
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
content: `The lat is ${lat} and the long is ${lng}`
});
const marker = new google.maps.Marker({
position: { lat, lng },
map: map
});
// And we add a listener to the marker so that
// it opens the infowindow when it is clicked
marker.addListener('click', () => {
infowindow.open(map, marker);
});
markers.push(marker);
}

试试这个:

position: {lat: castles[i][1], lng: castles[i][2]}

最新更新