Samsam Samsam - 3 days ago 6
Javascript Question

"google not defined" when integrating Maps API

I am trying to integrate Google Maps in my webapplication, but my code gives the error "google not defined".

Can someone help me figure it out? Thanks in advance.

</head><script src="http://maps.google.com/maps/api/js?key=AIzaSyAdXcTNKKaje1AtGQq32SwOMJ5Um-EE5GU " async="" defer="defer" type="text/javascript"></script>




<body> <div id="map" style="width: 400px; height: 300px;"></div><script type="text/javascript">
function LoadGoogle()
{ if(typeof google != 'undefined' && google && google.load)
{
var address = 'UK';

var map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.TERRAIN,
zoom: 6
});

var geocoder = new google.maps.Geocoder();

geocoder.geocode({
'address': address
},
function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
map.setCenter(results[0].geometry.location);
}
});
}
else
{
setTimeout(LoadGoogle, 30);
}
}
LoadGoogle(); </script></body>


Tried this also, still getting same error.

var map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.TERRAIN,
zoom: 6
});

var geocoder = new google.maps.Geocoder();

geocoder.geocode({
'address': address
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
map.setCenter(results[0].geometry.location);
}
});

Answer

You are deferring the Google library include, so when LoadGoogle() runs, the library has not necessarily been loaded.

2 ways to go about it :

  • For testing, remove async/defer from the include.

  • For production, make sure that your custom script runs after everything else has been loaded. The way to do this is by using the callback provided by google, so the script calls your LoadGoogle function on load.

<script src="http://maps.google.com/maps/api/js?key=AIzaSyAdXcTNKKaje1AtGQq32SwOMJ5Um-EE5GU&callback=LoadGoogle" async="async" defer="defer" type="text/javascript"></script>

Then in your script, don't call LoadGoogle()

Reference

Comments