Richard
Richard

Reputation: 1038

Google is not defined except it is

I use a module for prestashop that throw a googlemap. I want to change the position of the view dinamicaly, so I did a test like so:

document.addEventListener('DOMContentLoaded', function() {


    function moveToLocation(lat, lng){
    console.log(google);
        var center = google.maps.LatLng(lat, lng);
        // using global variable:
        map.panTo(center);
    }
    moveToLocation(48, 12);
});

The console give me an error Google is not defined so I checked my console and I found that

console return for 'window'

What am I doing wrong or misunderstanding here?

Edit My script is loaded before this :

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBCOuQvJWQQxSde3s5RNCBZmB1VkfFKXxw&amp;callback=AdvancedStoreMapsInitMap&amp;language=fr" async="" defer=""></script>

Upvotes: 2

Views: 467

Answers (2)

MrUpsidown
MrUpsidown

Reputation: 22486

How it works essentially and how Google instructs you to use their API is to load the script with async defer and provide a callback function as explained in the documentation.

All your map code should be within that callback function or called from within that function, which ensures the API is fully loaded before you try to access it.

The add-on you are using is loading the map and provides AdvancedStoreMapsInitMap as the callback function. If you don't have access to that part of the code, then you have a problem.

You could wait some time before executing your code, which should ensure that the API script has loaded. I said "should" because you cannot be sure it is loaded even if you wait 2 seconds or even more... (network issues, etc.)

Or you could check directly like that:

if (typeof google === 'object' && typeof google.maps === 'object') { ... }

You could check that multiple times with a timeout for example. And when it is, execute your code. A bit of a hack but that should work.

Also note that you can't include the API script multiple times on the same page. It will generate an error: You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.

Upvotes: 2

Siluxmedia
Siluxmedia

Reputation: 27

Try including the code inside a document load event instead of DOMContentLoaded.

$( document ).ready(function() {
    function moveToLocation(lat, lng){
    console.log(google);
        var center = google.maps.LatLng(lat, lng);
        // using global variable:
        map.panTo(center);
    }
    moveToLocation(48, 12);
});

Upvotes: 0

Related Questions