Google Maps APIで、クリックした後にのみ情報ウィンドウをロードします

Aug 17 2020

数百のGoogleマップマーカーがあり、その情報はデータベース(allDbEntries.length)から取得されます。各マーカーinfowindowは、ユーザーがマーカーをクリックすると開くに関連付けられています。それぞれinfoWindowのに1つ以上の画像のURLがあり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
  })
}

問題は、これをモバイルAPP(Android)またはモバイルブラウザーにも使用しており、マップが読み込まれるたびに、何百もの画像が自動的に読み込まれ、モバイルデバイスの帯域幅を消費することです。

htmlInfoContentマーカーをクリックした後にのみ、マーカーのコンテンツ(特に画像)をロードするにはどうすればよいですか?

開発ツールからわかるように、マップを開くたびに、すべての画像が読み込まれ、帯域幅を消費しすぎます

回答

JoãoPimentelFerreira Aug 24 2020 at 19:31

解決策を見つけました。をhtmlInfoContent配列に配置する必要があり、クリックイベントハンドラーを処理する関数を返す匿名の自己呼び出し関数を使用する必要がありました。このように、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))
}