I appreciate that it had been asked multiple times now, but I cannot find a way to resolve it and load the script with initMap function as a separate file.
Let me explain:
I am calling Google Maps API:
<script src="https://maps.googleapis.com/maps/api/js?key=MYAPIKEY&callback=initMap" async
defer></script>
Followed by my bundled main JS file that contains initMap function.
<script src="/js/main.js"></script>
And I have the error as in the title.
What I tried to do:
- load main.js first - same error.
- move both scripts in the head section - same error.
- load main.js second - same error.
- split both scripts calling between top of the page (head) and bottom (before end of body) (each way) - same error.
What works is to call the function within the page as per:
<script>
function initMap() {
//rest of the code
</script>
and put it after the api call.
I appreciate that this is the solution to the initial problem of the console error message, but I would like to initiate and call this function from within the main js file as I do with the rest of the JS.
Any help and explanation, would be appreciated :) Thanks
Edit 1 - added more code below and moved function to the top of th main.js file
So the main.js now looks like - webpack blob at the beginning followed by:
function initMap() {
var uluru = { lat: 40.741895, lng: -73.989308 };
var map = new google.maps.Map(document.getElementById('map'), _defineProperty({ center: { lat: 40.741895, lng: -73.989308 }, zoom: 14 }, 'center', uluru));
var marker = new google.maps.Marker({
position: uluru, map: map
});
}
the error still occurs and the map won`t load.
Edit 2 - more tests done after your comments and suggestions.
When I tried the global scope using the JS bin code it did not work either.
So, I exported manually the code to a separate file and now load it as
<script src="/js/Maps.js"></script>
and it works.
It indicates, that somehow webpack and babel are causing an issue... Maybe I should module.export the function somehow?
my main.js (prebundled - for webpack) looks like this:
require('./base/main');
require('./modules/Maps');
whilst the Maps.js (pre-bundled) does not have any export at the end.