user3348867
user3348867

Reputation: 11

Error: initMap is not a function

I have a unique problem, namely I have a social website with a lot of interesting places. Every place has a google map. And today I see a problem.

When I add new place with address to make map from google api, it doesn't work.

I was checked previously added places and they normally have map, though error

"initMap is not a function".

Whats wrong? Why in newly created places map from google api doesn't work? I use it with my api key:

 <script async defer src="https://maps.googleapis.com/maps/api/js?key=MY_API&callback=initMap"></script>

Upvotes: 1

Views: 5971

Answers (2)

oryxz
oryxz

Reputation: 31

Probably comes from script position in your code. Make sure;

<script src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY"></script>

load after script block containing initMap function.

<script type="text/javascript">
function initMap() {
 //
}
<script src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY"></script>

Upvotes: 3

Stephen Michael Hammit
Stephen Michael Hammit

Reputation: 977

Is there a function called "initMap" in your code? If not you will get this error. The async attribute lets the browser render the rest of your website while the Maps JavaScript API loads. When the API is ready, it will call the function specified using the callback parameter. If you want to have a different callback function with a different name, that is perfectly fine, but you will have to modify this request URL accordingly. You can also remove the callback parameter entirely if you wish to do so, but you will need to make a function call in your code to load the map. You will also need to remove async defer if you do this, otherwise you will get an error saying google is not defined. The modified script tag would be:

<script src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY"></script>

I have an example demonstrating this here:

https://jsfiddle.net/gy3yg9ma/11/

Please insert your own API key to use the sample. Notice how I had to call initMap(); manually in my code since I removed the callback parameter. The map will not load until a function is called to load it.

I hope this helps!

Upvotes: 1

Related Questions