Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX
Asked Answered
A

10

98

I have a page that uses the Google Maps API to display a map. When I load the page directly, the map appears. However, when I try to load the page using AJAX, I get the error:

Uncaught ReferenceError: google is not defined

Why is this?

This is the page with the map:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var mapOptions = { zoom:7, mapTypeId: google.maps.MapTypeId.ROADMAP, center: chicago }
  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
  directionsDisplay.setMap(map);
}
$(document).ready(function(e) { initialize() });
</script>
<div id="map_canvas" style="height: 354px; width:713px;"></div>

And this the page with the AJAX call:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(e) {
    $('button').click(function(){
        $.ajax({
            type: 'GET', url: 'map-display',
            success: function(d) { $('#a').html(d); }
        })
    });
});
</script>
<button>Call</button>
<div id="a"></div>
</body>
</html>

Thanks for your help.

Applicatory answered 9/1, 2013 at 6:44 Comment(0)
S
97

The API can't be loaded after the document has finished loading by default, you'll need to load it asynchronous.

modify the page with the map:

<div id="map_canvas" style="height: 354px; width:713px;"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize"></script>
<script>
var directionsDisplay,
    directionsService,
    map;

function initialize() {
  var directionsService = new google.maps.DirectionsService();
  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var mapOptions = { zoom:7, mapTypeId: google.maps.MapTypeId.ROADMAP, center: chicago }
  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
  directionsDisplay.setMap(map);
}

</script>

For more details take a look at: https://mcmap.net/q/218733/-async-google-maps-api-v3-undefined-is-not-a-function-closed/14185834#14185834

Example: http://jsfiddle.net/doktormolle/zJ5em/

Shoshanashoshanna answered 9/1, 2013 at 12:45 Comment(3)
Thanks! Makes perfect sense now. Just had a follow-up: my map is coming in all grayed out (with Google logo, link and terms of use though). I can see in Firebug that the tiles are loading. Do you know what the reason might be?Applicatory
Usually this is a result of a missing/invalid map-option like zoom, mapTypeId or center(all of them are required, when they are missing or an invalid value has been assigned, there is no default-value for a fallback, the map could not be rendered)Shoshanashoshanna
The problem has to do with the fact that I'm hiding the div in which the map appears. I have a separate question for that here: #14263972Applicatory
I
43

I know this answer is not directly related to this questions' issue but in some cases the "Uncaught ReferenceError: google is not defined" issue will occur if your js file is being called prior to the google maps api you're using...so DON'T DO this:

<script type ="text/javascript" src ="SomeJScriptfile.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
Ineradicable answered 16/7, 2014 at 3:57 Comment(2)
my google maps api include is above my self defined js, still getting this error though but not all the time. Sometimes, it loads just fine. I need to trap this error but I have no idea what's the cause.Joejoeann
@Joejoeann reference accepted answer in the link below. I think it covers the majority of instances where you should be particularly concerned about the order of your JScript library files. You may also want to consider using asynchronous connection to better manage this as suggested in the original answer for this thread. #4988477Ineradicable
V
14

Uncaught ReferenceError: google is not defined error will be gone when removed the async defer from the map API script tag.

Verlaverlee answered 7/5, 2019 at 7:45 Comment(0)
R
8

At a guess, you're initialising something before your initialize function:

var directionsService = new google.maps.DirectionsService();

Move that into the function, so it won't try and execute it before the page is loaded.

var directionsDisplay;
var directionsService;
var map;

function initialize() {
  directionsService = new google.maps.DirectionsService();
  directionsDisplay = new google.maps.DirectionsRenderer();
}
Recording answered 9/1, 2013 at 9:7 Comment(0)
P
4

What worked for me after following all your workarounds was to call the API:

 <script async defer src="https://maps.googleapis.com/maps/api/js?key=you_API_KEY&callback=initMap&libraries=places"
            type="text/javascript"></script>

before my : <div id="map"></div>

I am using .ASP NET (MVC)

Pescara answered 30/7, 2019 at 12:50 Comment(0)
C
1

I tried on different browsers and the answer for me was that is very important have in script tag this type="text/javascript"

It's very important to add to every js script for browser compatibility

<script type="text/javascript" src="ANY_FILE_OR_URL"></script>

After this the issues like Uncaught ReferenceError: google is not defined or others (that can't load any referece are gone)

Corella answered 28/3, 2021 at 0:0 Comment(1)
Well yes, that applies to any JS file, not just this oneNessa
A
0

Uncaught ReferenceError:

google is not defined, google related stuff has not been loaded yet and we are using it that causes this error. In the following code snippet, we see both cases will generate the error. We can move the definition of google related stuff inside initMap method or load the function in question a little base later.

    //shows the error 
    google.maps.Polygon.prototype.getBounds1 = function (latLng) {
    ...
    };
   function initMap() {
   ...
   //should be here inside the initMap
   }
    //error with the following
    google.maps.Polygon.prototype.getBounds1 = function (latLng) {
        ...
    };
Aldana answered 13/7, 2022 at 20:59 Comment(0)
B
0

In my case non of above solution work....due to not loading google script. So I just checking recursively ...when google loaded it will call original function.

function checkMapLoaded() {
  if (typeof google === "undefined") {
    setTimeout(checkMapLoaded, 1000);
  } else {
    // do some work here
    initSchMap();
  }
}
Banish answered 14/9, 2022 at 8:35 Comment(1)
Your answer could be improved by adding more information on what the code does and how it helps the OP.Audy
S
0

If using a partial render function, render the google script and your script in the same render space.

In my ASP.Net Core web app, I was rendering the google script in the head using @section head {...} and my custom script outside the @section head {...}.

So either put both scripts tag in the @section head{...} or outside of it.

Scavenge answered 10/1, 2023 at 22:24 Comment(0)
H
-1

For me

Adding this line

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

Before this line.

<script id="microloader" type="text/javascript" src=".sencha/app/microloader/development.js"></script>

worked

Hurtado answered 30/1, 2016 at 16:43 Comment(1)
Yes, that's what this answer saysNessa

© 2022 - 2024 — McMap. All rights reserved.