在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 }) } (特别是图像)的内容加载到标记中?

从开发工具中可以看到,每次我打开地图时,所有图像都会加载,占用太多带宽

enter image description here

解决方法

找到了解决方案。我必须将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))
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...