I’m having issues getting my Google Maps integration to function using Vanilla JavaScript. I followed a tutorial and inserted my API Key but still faced problems. My online project shows an error, which states: ReferenceError: google is not defined at initMap. Here’s my code snippet from index.html:
<!DOCTYPE html>
<html>
<head>
<title>Add Map</title>
<meta charset="UTF-8">
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script>
let myMap;
async function loadMap() {
const coordinates = { lat: -25.344, lng: 131.031 };
const { Map } = await google.maps.importLibrary("maps");
myMap = new Map(document.getElementById('mapContainer'), {
zoom: 4,
center: coordinates,
});
}
loadMap();
</script>
</head>
<body>
<h3>Google Maps Example</h3>
<div id='mapContainer'></div>
</body>
</html>
Hi Grace_31Dance,
This error often occurs when the Google Maps JavaScript API isn't loaded properly in your HTML file before you try to access it. Follow these steps to fix the issue and get your map up and running:
- Add the Google Maps JavaScript API script tag in the
<head>
section of your HTML file.
- Ensure that you replace
YOUR_API_KEY
with your actual API key.
- Modify your code to load and initialize the map correctly.
Here's an updated version of your code:
<!DOCTYPE html>
<html>
<head>
<title>Add Map</title>
<meta charset="UTF-8">
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>
<script>
let myMap;
function initMap() {
const coordinates = { lat: -25.344, lng: 131.031 };
myMap = new google.maps.Map(document.getElementById('mapContainer'), {
zoom: 4,
center: coordinates,
});
}
</script>
</head>
<body>
<h3>Google Maps Example</h3>
<div id='mapContainer' style='width: 100%; height: 100%;'></div>
</body>
</html>
Ensure you replace YOUR_API_KEY
with your actual Google Maps API key. This code will set the initMap
function as the callback, ensuring the Google Maps API is fully loaded before your map is initialized.
Let me know if you have further issues!
To expand on Finn_Mystery's solution, there's a subtle but important point to consider when integrating Google Maps with your JavaScript: the timing of when your script loads and when it attempts to access the Google Maps library.
Although adding the script tag correctly as suggested: <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>
often resolves the issue, it's worth looking into an alternate approach using Promises for better control over asynchronous operations in JavaScript.
Here's a modern way to achieve this:
<!DOCTYPE html>
<html>
<head>
<title>Add Map</title>
<meta charset="UTF-8">
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script>
function loadScript(url) {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.async = true;
script.defer = true;
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
}
loadScript('https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY')
.then(() => {
const coordinates = { lat: -25.344, lng: 131.031 };
new google.maps.Map(document.getElementById('mapContainer'), {
zoom: 4,
center: coordinates,
});
})
.catch(error => console.error('Error loading Google Maps', error));
</script>
</head>
<body>
<h3>Google Maps Example</h3>
<div id='mapContainer' style='width: 100%; height: 100%;'></div>
</body>
</html>
Here's how it works:
- A custom function,
loadScript()
, dynamically adds the Google Maps script to the document and returns a Promise.
- Upon successful loading, the Promise resolves, allowing you to then initialize the map. This ensures that the map initialization occurs only after the Google Maps JavaScript library is completely loaded.
This approach leverages Promises providing a structured way to handle asynchronous code elegantly.
Hey Grace_31Dance,
The error you're seeing usually means that the Google Maps API script isn't correctly loaded before your code tries to use it. You need to add the Google Maps API script with a callback to initialize the map.
Here's an updated version of your code:
<!DOCTYPE html>
<html>
<head>
<title>Add Map</title>
<meta charset="UTF-8">
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script>
function initMap() {
const coordinates = { lat: -25.344, lng: 131.031 };
new google.maps.Map(document.getElementById('mapContainer'), {
zoom: 4,
center: coordinates,
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>
</head>
<body>
<h3>Google Maps Example</h3>
<div id='mapContainer' style='width: 100%; height: 100%;'></div>
</body>
</html>
Replace YOUR_API_KEY
with your actual key. With the callback=initMap
, this ensures the map loads only after the API script is ready. Let me know how it goes!