Google Maps API throws Uncaught ReferenceError: google is not defined only when using AJAX

Google Maps API throws Uncaught ReferenceError: google is not defined only when using AJAX

The API cant be loaded after the document has finished loading by default, youll 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://stackoverflow.com/questions/14184956/async-google-maps-api-v3-undefined-is-not-a-function/14185834#14185834

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

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 youre using…so DONT 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>

Google Maps API throws Uncaught ReferenceError: google is not defined only when using AJAX

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

Leave a Reply

Your email address will not be published.