L
L
ligisayan2020-07-08 09:38:42
JavaScript
ligisayan, 2020-07-08 09:38:42

How to check if there is a need to load google maps on a page?

Hello!

There is a dynamically loaded Google map, which is only needed on the contact page, and I have a single script connected to all pages. When navigating through pages, I periodically get the following error:

You have included the Google Maps API multiple times on this page,


and if I display the connection of the maps.googleapis.com script only on the contact page, then the error is already
google is not defined
,
although in the first and second cases the map itself is loaded.

How to get rid of errors?

<script defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA3XfuMJJGzaU8TUItQM7XWD4esZdbpgtA"></script>
<div id="w3docs-map"></div>

function initialize() {
  var prop = {
    center: new google.maps.LatLng(51.508742, -0.120850),
    zoom: 5,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("w3docs-map"), prop);
}
google.maps.event.addDomListener(window, 'load', initialize);

#w3docs-map {
  width:500px;
  height:380px;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrew, 2020-07-08
@ligisayan

function initialize() {
var _map = document.getElementById("w3docs-map");
if(!_map.firstChild){
  var prop = {
    center: new google.maps.LatLng(51.508742, -0.120850),
    zoom: 5,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(_map, prop);
}
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question