我基本上试图实现与Airbnb非常相似的地图。我展示了一系列的InfowDows,以显示每个租赁位置的价格。当我单击InfowDindow时,我将显示另一个Infowdow(命名popup
),其中包括位置详细信息。
我已经在infowindow
元素中添加了一个事件侦听器,但是当我单击地图上的任何InfowIndows时,我只会在数组中获得最后一个结果的弹出窗口。
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 });
},
您在循环中进行操作,因此,当循环越过弹出窗口时,它的最后值:
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
循环结束时。
您需要为每个点创建一个新的弹出窗口(但这是在资源消费),或者每次单击标记时每次创建新的弹出窗口。对于第二个创建单独的功能,请将一些数据传递给它并创建一个新的弹出窗口。
希望,它会有所帮助。