我基本上是在尝试实现与Airbnb十分相似的地图。我已经显示了一系列信息窗口,以显示每个租赁位置的价格。当我单击一个信息窗口时,我将显示另一个带有位置详细信息的信息窗口(名为popup
)。
我已经向infowindow
元素添加了一个事件侦听器,但是当我单击地图上的任何信息窗口时,我只会在数组中弹出最后一个结果。
methods: {
initMap() {
var map = new google.maps.Map(document.getElementById("camp-map"), {
zoom: 2,
center: { lat: this.latitude, lng: this.longitude },
mapTypeId: 'satellite',
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.RIGHT_BOTTOM
},
mapTypeControl: false,
scaleControl: false,
streetViewControl: false,
rotateControl: false,
fullscreenControl: false
});
this.popup = new google.maps.InfoWindow({
content: "nothing yet..."
});
return map;
},
addInfoWindows(map) {
// Get total lat & total lng to center the map on new results
let totalLat = 0;
let totalLng = 0;
// Iterate over all of the camps
for (var i = 0; i < this.filteredCamps.length; i++) {
let latitude = this.filteredCamps[i].coordinates.lat;
let longitude = this.filteredCamps[i].coordinates.lng;
let id = this.filteredCamps[i].id;
let slug = this.filteredCamps[i].slug;
let name = this.filteredCamps[i].name;
let price = this.filteredCamps[i].priceAvg.toLocaleString("en");
let image = this.filteredCamps[i].mainImage;
let country = this.filteredCamps[i].country;
let type = this.filteredCamps[i].type;
totalLat += parseFloat(latitude);
totalLng += parseFloat(longitude);
// create a HTML element for each spot
var el = document.createElement("div");
el.innerHTML =
'<div><div class="marker-tooltip"></div>$' + price + "</div>";
el.className = "camp-map-marker";
var infowindow = new google.maps.InfoWindow({
content: el,
position: { lat: latitude, lng: longitude },
map: this.map,
});
// Create popup view
var div = ....
this.popup = new google.maps.InfoWindow({
content: div,
position: { lat: latitude, lng: longitude },
});
// On infowindow click center and popup
el.addEventListener("click", () => {
console.log('clicked: ')
this.map.setCenter({ lng: longitude, lat: latitude })
this.popup.setContent(div);
this.popup.open(this.map, infowindow)
});
this.gMarkers.push(infowindow);
}
let arrayLength = this.gMarkers.length
let currentLat = totalLat / arrayLength
let currentLng = totalLng / arrayLength
this.map.setCenter({ lat: currentLat, lng: currentLng });
},
答案 0 :(得分:0)
您在循环中进行操作,因此当循环结束时,弹出窗口具有最后一个值:
this.popup = new google.maps.InfoWindow({
content: div,
position: { lat: latitude, lng: longitude },
});
从这里:
let latitude = this.filteredCamps[i].coordinates.lat;
let longitude = this.filteredCamps[i].coordinates.lng;
其中
i = this.filteredCamps.length
循环结束时。
您需要为每个点创建一个新的弹出窗口(但这很耗资源),或者每次单击标记时都创建一个新的弹出窗口。对于第二个,创建一个单独的函数,将一些数据传递给它,然后创建一个新的弹出窗口。
希望,它会有所帮助。