Reputation: 436
I am working with the example that I have found on the google documentation: https://developers.google.com/maps/documentation/javascript/tutorial#asynch
I have juste copy/pasted the hello world code and it's working fine: it display me a map at the specified location. But now I would like to be able to work in this map in a JS file to a much readable work, so I just added <script src="RunUTrail.js"></script>
just before the </body>
.
This file contains the exact same method found in the <script>
:
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397,lng: 150.644},
zoom: 8
});
So it should do nothing but I have the ReferenceError: google is not defined
. What am I missing to use the API insinde a JS file?
Upvotes: 0
Views: 135
Reputation: 119
You need to put your js code for map display in a callback function like initMap() and add the name of the callback function in google maps script source.
HTML Code:
<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>
JS Code:
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
Upvotes: 1