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