I know this question has been asked. But I still can't get past it. I am simply trying to get googlemaps API loaded in js fiddle. I cannot get past the error:initMap is not a function. My jsfiddle here: jsfiddle
My code:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 34.397, lng: 150.644 },
scrollwheel: false,
zoom: 2
});
HTML:
<div id="map" style="width: 500px; height: 400px;"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
When I have the function initmap(){} (with brackets) the map does not load and I get the error.
When remove the function initmap{}
and just:
var map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 34.397, lng: 150.644 },
scrollwheel: false,
zoom: 2
});
The map loads, however I still get the error:
initMap is not a function
It might have something to do with a callback. I have not written javascript in a while. But I just need to get past this error. Thanks
Here's a JSFiddle of how it works.
Essentially place your function above the call to Google API
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 34.397, lng: 150.644 },
scrollwheel: false,
zoom: 2
});
} // close function here
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDieZ7uAY4DPdT3Z4fp4KtykHl6dWryYdw&callback=initMap">
</script>
Also the function wasn't properly closed.
In the fiddle, you have a syntax error in not closing the iniMap()
with }
. Besides, the function is defined after the DOM loads. To fix this:
<body>
or <head>
Here's how to deal with these.
Place initMap
in the global scope. do not wrap the function definition within a private or anonymous scope like
(function(){
function initMap(){
//
}
})();
Define the function in the <head>
if possible. or at least before loading the API in <body>
. And never define initMap
after the dom completely loads like window.onload
and document.addEventListener('ondomready', callback)
Good practice
<script>
function initMap(){
//
}
</script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
Bad practices:
window.onload
<script>
window.onload = function(){
function initMap(){
//
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
And
<script>
document.addEventListener('ondomready', function(){
function initMap(){
//
}
});
</script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
Or $(function(){ })
if you are using jQuery
<script>
$(function(){
function initMap(){
//
}
});
</script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With