How to decrease the google maps API hit count by calling it only when user scrolls to the particular section

Is there any way by which I can call google maps API only when the user scrolls to the maps section and not on page hit?

Below is the code I am using to call google maps API in angularJs:

 function _initializeMap() {
        if(!angular.isDefined(window.google) || !angular.isDefined(window.google.maps)){
            $ocLazyLoad.load("js!https://maps.googleapis.com/maps/api/js?key=Sample_Google_API_Key").then(function() {
                $ocLazyLoad.load("js!"+window.file_base+"./libs/markerclusterer.js").then(function() {
                    initMap();
                });
            });
        }
        else{
            initMap();
        }
    }

Answer

Intersection observer solves the problem:

Here I have created a wrapper over the _initializeMap i.e initializeMap function which calls _initializeMap on user scroll to the div having id ‘map-canvas’ which consists of google map resulting in fewer google maps API calling.

 function initializeMap() {

        var options = {
          rootMargin: '200px',
          threshold: 0
        }

        var map = document.getElementById('map-canvas')

        var observer = new IntersectionObserver(
          function(entries, observer) {
            var isIntersecting = typeof entries[0].isIntersecting === 'boolean' ? entries[0].isIntersecting : entries[0].intersectionRatio > 0
            if (isIntersecting) {
              _initializeMap();
              observer.unobserve(map)
            }
          },
          options
        )

        observer.observe(map)

   }

Leave a Reply

Your email address will not be published. Required fields are marked *