#Google maps
1 messages · Page 1 of 1 (latest)
Hi @topaz niche. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Astro components run on the server, so you can’t access browser-specific objects like window within the frontmatter. This is likely why you're encountering the "window is not defined" error when trying to use the Google Maps loader.
Here's how you can resolve this issue:
-
Determine the code that calls
window. If you aren’t usingwindowdirectly and still getting this error, check to see if any packages you’re importing are meant to run on the client. -
If the code is in an Astro component, move it to a
<script>tag outside of the frontmatter. This tells Astro to run this code on the client, wherewindowis available. -
If the code is in a framework component, try to access these objects after rendering using lifecycle methods (e.g.
useEffect()in React,onMounted()in Vue, andonMount()in Svelte). Tell the framework component to hydrate client-side by using aclient:directive, likeclient:load, to run these lifecycle methods. You can also prevent the component from rendering on the server at all by adding theclient:onlydirective.
Here's an example of how you might adjust your code:
<!-- Example: Load Google Maps on a single page. -->
<script client:only>
import { Loader } from "@googlemaps/js-api-loader";
const loader = new Loader({
apiKey: "YOUR_API_KEY",
version: "weekly",
});
loader.load().then(() => {
const map = new google.maps.Map(document.getElementById("map"), {
center: { lat: -34.397, lng: 150.644 },
zoom: 8,
});
});
</script>
Please replace "YOUR_API_KEY" with your actual Google Maps API key.
For more information, you can refer to the Astro Troubleshooting Guide (https://docs.astro.build/en/guides/troubleshooting/).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@topaz niche kapa.ai is still learning and improving, please let us know how it did by reacting below