问题描述
我有数百个Google Maps标记,这些标记的信息是从数据库(allDbEntries.length
)中获取的,每个标记都与infowindow
关联,该标记在用户单击标记后打开。每个infoWindow
的{{1}}中都有一个或多个图片的URL。
htmlInfoContent
问题是我正在为移动APP(Android)甚至移动浏览器使用它,并且每次加载地图时,都会自动加载数百张图像,从而消耗移动设备的带宽。
仅在单击标记后,如何才能将const map = new google.maps.Map(document.getElementById('map'),mapOptions)
// Add the markers and infowindows to the map
for (var i = 0; i < allDbEntries.length; i++) {
const el = allDbEntries[i]
const marker = new google.maps.Marker({
position: { lat: el.data_coord_latit,lng: el.data_coord_long },map: map,title: el.car_brand + ' ' + el.car_model
})
var htmlInfoContent = ''
for (var photoIndex = 1; photoIndex <= 4; photoIndex++) {
if (el['foto' + photoIndex]) {
const photoUrl = requestImageUrl + el['foto' + photoIndex]
htmlInfoContent += `<img width="200" src="${photoUrl}"><br>`
}
}
const infowindow = new google.maps.InfoWindow({
content: htmlInfoContent
})
marker.addListener('click',(e) => {
infowindow.open(map,marker)
return true
})
}
(特别是图像)的内容加载到标记中?
从开发工具中可以看到,每次我打开地图时,所有图像都会加载,占用太多带宽
解决方法
找到了解决方案。我必须将htmlInfoContent
放入一个数组中,并且必须使用一个匿名的自调用函数,该函数返回处理click事件处理程序的函数。这样,仅在单击标记后 设置html内容。
const map = new google.maps.Map(document.getElementById('map'),mapOptions)
const infowindow = new google.maps.InfoWindow()
var htmlInfoContent = []
// Add the markers and infowindows to the map
for (var i = 0; i < allDbEntries.length; i++) {
const el = allDbEntries[i]
const marker = new google.maps.Marker({
position: { lat: el.data_coord_latit,lng: el.data_coord_long },map: map,title: el.car_brand + ' ' + el.car_model
})
var htmlInfoContent[i] = ''
for (var photoIndex = 1; photoIndex <= 4; photoIndex++) {
if (el['foto' + photoIndex]) {
const photoUrl = requestImageUrl + el['foto' + photoIndex]
htmlInfoContent[i] += `<img width="200" src="${photoUrl}"><br>`
}
}
google.maps.event.addListener(marker,'click',(function (marker,i) {
return function () {
infowindow.setContent(htmlInfoContent[i])
infowindow.open(map,marker)
}
})(marker,i))
}