Lazy load map when they come into the viewport

Hello,

I am trying to load a Google Map map only when it is displayed on the viewport.
I would like the card to load only when I arrive on it, only when the user sees it on his screen

I have heard a lot about the “lazy loading” principle, but I must admit that I start in javascript.

My code works perfectly on desktop, but I would like that my mobile site is much better.

Here is my code:

   function initMap() {
        var loc = {lat: 45.764043, lng: 4.835658999999964};
        var map = new google.maps.Map(document.getElementById('map'), {
            center: loc
        });
        var bounds = new google.maps.LatLngBounds();
        var coordinate = document.getElementsByClassName('datajson');
        for (var i = 0; i < coordinate.length; i++) {
            (function (index) {
                var elements = JSON.parse(coordinate[i].value);
                var localisation={lat: elements.latitude, lng: elements.longitude};
                var marker = new google.maps.Marker({
                    position:localisation,
                    map: map
                });
                bounds.extend(localisation);
            })(i);
        }
        map.setCenter(bounds.getCenter());
        map.setZoom(10);  
    }

    function loadScript() {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'https://maps.googleapis.com/maps/api/js?key=XXXXX&'+'callback=initMap';
        document.body.appendChild(script);
    }

    window.onload = loadScript;

I would like to have your opinion on the way to do and possible improvements if possible.

I thank you in advance

I did this a few months ago. You can use the intersection observer API

However you will need a polyfill if you wish to support ie11

This blog post helped me a lot

https://walterebert.com/playground/wpo/google-maps/

2 Likes

thank you for your answer, it helped me a lot :slight_smile: