FYI, I\'m not a JavaScript Ninja but felt like I\'ll become one when I did a lot of things based on Google Maps recently.
I implemented a map. User can search for go
Had the same issue while following the Google Tutorial. In my case the problem turned out to be the async
keyword, which was causing the Google Maps script to execute asynchronously while the rest of the page continued parsing. Here's the fix:
defer
keyword and not the async
keyword. Code:<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places$callback=YourFunctionHere" defer></script>
Using defer
makes sure the script is executed when the page has finished parsing (source).
For Angular
I was initializing the autocomplete
in ngOnInit()
because of which I was getting the error.
I simply moved the initialization to ngAfterViewInit()
and everything worked fine.
Code:
ngAfterViewInit(): void {
this.autocomplete = new google.maps.places.Autocomplete(
(this._document.getElementById('input')),
{ types: ['geocode'] }
);
}
This is an issue of DOM. Your javascript loads before loading your html document.
Make sure your html elements load first and then only load javascript.
Like
and then
Your javascript codeI had the same problem in Angular2. My solution is to move the initialisation of Google Maps to a function that fires when a user focus in the autocomplete input
field. Not the most beautiful solution, but it works.
Code:
private autocomplete_init: boolean: false;
autocompleteFocus() {
this.autocomplete_init = true;
if (!this.autocomplete_init) {
this._autocomplete = new google.maps.places.Autocomplete(document.getElementById("search_address"), {
componentRestrictions: {'country': 'dk'}
}
}
HTML:
<input placeholder="Search" type="text" id="search_address" (focus)="autocompleteFocus()" autofocus>
This has been my problem while following the tutorial on Google.
The problem is that you should execute the javascript after the page loads, you can call the function on the GET
parameter while calling the Google Map script:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places$callback=YourFunctionHere"></script>
YourFunctionHere
is a callback function means it will only execute after the page loads.
Or you can can call functions after the page loads. Example: window.onload = Yourfunction();
Now, inside that function is where you would do your Google Maps API stuff like document.getElementById('source_map')
and all methods that belong to the google
class.
.pac-container { z-index: 1051 !important; }