IntersectionObserver API with Google Maps

Here is an example of lazy loading a Google Map with intersection observer. It uses a Polyfill for browsers that lack support for IntersectionObserver.

Scripts are loaded using Filament Group loadJS.


<script>
function google_maps_init() {
  'use strict'

  var roemerberg = {lat: 50.110, lng: 8.682}

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 15,
    center: roemerberg
  })

  var marker = new google.maps.Marker({
    position: roemerberg,
    map: map
  })
}

function google_maps_lazyload(api_key) {
  'use strict'

  if (api_key) {
    var options = {
      rootMargin: '100px',
      threshold: 0
    }

    var map = document.getElementById('map')

    var observer = new IntersectionObserver(
      function(entries, observer) {
        // Intersecting with Edge workaround https://calendar.perfplanet.com/2017/progressive-image-loading-using-intersection-observer-and-sqip/#comment-102838
        var isIntersecting = typeof entries[0].isIntersecting === 'boolean' ? entries[0].isIntersecting : entries[0].intersectionRatio > 0
        if (isIntersecting) {
          loadJS('https://maps.googleapis.com/maps/api/js?callback=google_maps_init&key=' + api_key)
          observer.unobserve(map)
        }
      },
      options
    )

    observer.observe(map)
  }
}

google_maps_lazyload("YOUR_GOOGLE_MAPS_API_KEY")
</script>

Römerberg, Frankfurt am Main, Germany

By: Walter Ebert