บน Google Maps API ให้โหลดหน้าต่างข้อมูลหลังจากคลิกเท่านั้น

Aug 17 2020

ฉันมีเครื่องหมาย Google Maps หลายร้อยรายการซึ่งดึงข้อมูลมาจากฐานข้อมูล ( allDbEntries.length) แต่ละเครื่องหมายเชื่อมโยงกับเครื่องหมายinfowindowซึ่งจะเปิดขึ้นหลังจากที่ผู้ใช้คลิกที่เครื่องหมาย แต่ละคนinfoWindowมีหนึ่งหรือ 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
  })
}

ปัญหาคือฉันใช้สิ่งนี้กับแอพมือถือ (Android) หรือแม้แต่เบราว์เซอร์มือถือและทุกครั้งที่โหลดแผนที่ภาพหลายร้อยภาพจะถูกโหลดโดยอัตโนมัติโดยใช้แบนด์วิดท์ของอุปกรณ์เคลื่อนที่

ฉันจะโหลดเนื้อหาของhtmlInfoContent(โดยเฉพาะรูปภาพ) ในเครื่องหมายหลังจากคลิกที่เครื่องหมายนั้นได้อย่างไร

ดังที่คุณเห็นจาก Dev Tools ทุกครั้งที่ฉันเปิดแผนที่รูปภาพทั้งหมดจะถูกโหลดโดยใช้แบนด์วิดท์มากเกินไป

คำตอบ

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