Sull'API di Google Maps, carica le infowindow solo dopo il clic
Ho diverse centinaia di indicatori di Google Maps le cui informazioni vengono recuperate da un database ( allDbEntries.length
), ogni indicatore associato a un indicatore infowindowche si apre dopo che l'utente fa clic su un indicatore. Ognuno infoWindow
ha uno o più URL dell'immagine nel proprio file 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
})
}
Il problema è che lo sto utilizzando per un'APP mobile (Android) o anche per browser mobili, e ogni volta che viene caricata la mappa vengono caricate automaticamente centinaia di immagini consumando la larghezza di banda del dispositivo mobile.
Come posso caricare il contenuto di htmlInfoContent
(in particolare le immagini) in un marker solo dopo aver cliccato su quel marker?
Come puoi vedere da Dev Tools, ogni volta che apro la mappa, tutte le immagini vengono caricate consumando troppa larghezza di banda

Risposte
Trovato la soluzione. Ho dovuto mettere il htmlInfoContent
in un array e ho dovuto usare una funzione auto invocante anonima che restituiva la funzione che si occupa del gestore di eventi click. In questo modo il contenuto html viene impostato solo dopo aver cliccato sul marker.
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))
}