如何解决在Google Maps API上,仅在单击后加载信息窗口
我有数百个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))
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。