Search code examples
google-maps-api-3cordova-plugins

On Google Maps API, load infowindow only after click


I have several hundreds of Google Maps markers whose info is fetched from a database (allDbEntries.length), each marker associated with a infowindow which opens after the user clicks on a marker. Each infoWindow has one or more image's URLs in its htmlInfoContent.

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
  })
}

The problem is that I'm using this for a mobile APP (Android) or even for mobile browsers, and every time the map is loaded, hundreds of images are loaded automatically consuming the bandwidth of the mobile device.

How can I load the content of htmlInfoContent (particularly images) in a marker only after clicking on that marker?

As you can see from Dev Tools, every time I open the map, all the images are loaded consuming too much bandwidth

enter image description here


Solution

  • Found the solution. I had to put the htmlInfoContent in an array, and I had to use an anonymous self-invoking function which returned the function which deals with the click event handler. In this way the html content is only set after the marker is clicked.

    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))
    }