To add Google Maps to an Astro site, paste the iframe from Google Maps’ “Share, Embed a map” option into a component and add loading="lazy", or use the Maps Embed API with an API key for more control. For the fastest pages, show a static preview or a “Get directions” link first and load the interactive map only when the visitor clicks. A Google Maps embed is one of the heaviest things a small business page can load, so how you load it matters more than which map you choose.
This guide covers each option on Astro 7, from a plain link to an interactive Leaflet map, with code you can copy.
Key Takeaways
- A Google Maps iframe loads a large amount of JavaScript;
loading="lazy"defers it until the map nears the viewport.- A click-to-load facade keeps the map off the critical path entirely.
- Google Maps URLs (
/maps/search/?api=1and/maps/dir/?api=1) give you search and directions links with no key and no script.- The Maps Embed API needs a key but gives you place, directions and search modes.
- Leaflet with an OpenStreetMap-based tile provider is a lighter interactive alternative.
Pick the lightest map that does the job
Most sites show a map for one reason: to help someone find a place. That rarely needs a fully interactive map on page load.
| Option | JavaScript on page load | API key | Interactive | Best for |
|---|---|---|---|---|
| Directions link | None | No | Opens Google Maps | Footers, mobile visitors |
| Lazy iframe | None until near viewport | No | Yes | Contact page, below the fold |
| Click-to-load facade | None until click | No (or Embed API key) | After click | Above-the-fold maps |
| Maps Embed API iframe | Same as iframe | Yes | Yes | Place, directions or search views |
| Leaflet map | Leaflet (small) plus tiles | Depends on tile provider | Yes | Custom markers, many locations |
| Maps JavaScript API | Large | Yes, billed | Fully | Apps built on Google’s map data |
Astro helps here because a component renders to plain HTML and adds no JavaScript unless you ask for it. The rest of this guide goes down that table from lightest to heaviest.
Start with a directions link
On phones, a link that opens the Google Maps app is often more useful than an embedded map. Google Maps URLs are documented, need no API key, and work on every device:
---
// src/components/DirectionsLink.astro
interface Props {
destination: string;
label?: string;
}
const { destination, label = 'Get directions' } = Astro.props;
const href = `https://www.google.com/maps/dir/?api=1&destination=${encodeURIComponent(destination)}`;
---
<a href={href} rel="noopener" target="_blank">{label}</a>
<DirectionsLink destination="Northside Plumbing, 412 Mill Road, Springfield, IL 62701" />
Use https://www.google.com/maps/search/?api=1&query=... instead to open the place itself. Including the business name with the address helps Google match the right listing. This costs nothing in performance and is a good default for footers and location pages, especially for local SEO on Astro sites, where the address text itself matters more than the map.
Embed a Google Map with a lazy iframe
For a visible map, open the place in Google Maps, choose Share, then Embed a map, and copy the iframe. Wrap it in a component so every page uses the same settings:
---
// src/components/GoogleMap.astro
interface Props {
src: string;
title: string;
}
const { src, title } = Astro.props;
---
<div class="map">
<iframe
src={src}
title={title}
loading="lazy"
referrerpolicy="no-referrer-when-downgrade"
allowfullscreen
></iframe>
</div>
<style>
.map {
aspect-ratio: 4 / 3;
width: 100%;
}
.map iframe {
width: 100%;
height: 100%;
border: 0;
}
</style>
Pass the src value from Google’s embed code (it starts with https://www.google.com/maps/embed?pb=). loading="lazy" stops the browser from fetching the map until it’s close to the viewport, so a map at the bottom of a contact page doesn’t affect the initial load. The aspect-ratio wrapper reserves the space so nothing shifts when the iframe appears.
The limit of a lazy iframe: once it’s in view, the full map loads whether the visitor wants it or not. For a map near the top of the page, use a facade.
Use the Maps Embed API for more control
The Maps Embed API offers the same iframe, built from URL parameters instead of an opaque pb= string. It needs an API key from Google Cloud, and Google lists Embed API requests as no-charge, but check the current Google Maps Platform pricing before relying on that.
---
// src/components/PlaceMap.astro
interface Props {
query: string;
title: string;
zoom?: number;
}
const { query, title, zoom = 15 } = Astro.props;
const key = import.meta.env.PUBLIC_GOOGLE_MAPS_EMBED_KEY;
const src = `https://www.google.com/maps/embed/v1/place?key=${key}&q=${encodeURIComponent(query)}&zoom=${zoom}`;
---
<iframe
src={src}
title={title}
width="600"
height="450"
loading="lazy"
referrerpolicy="no-referrer-when-downgrade"
style="border:0; width:100%; height:auto; aspect-ratio:4/3"
></iframe>
The key appears in your HTML, so it’s public by design. Protect it in Google Cloud Console: restrict it to the Maps Embed API only and to HTTP referrers on your domains. Besides place, the Embed API supports directions, search, view and streetview modes; see Google’s Maps Embed API documentation for the parameters each one takes.
Build a click-to-load map facade
A facade shows a static preview with a button. The map iframe loads only when clicked, so it never costs anything on page load:
---
// src/components/MapFacade.astro
import type { ImageMetadata } from 'astro';
import { Image } from 'astro:assets';
interface Props {
embedSrc: string;
title: string;
preview: ImageMetadata;
directions: string;
}
const { embedSrc, title, preview, directions } = Astro.props;
---
<map-facade data-src={embedSrc} data-title={title}>
<Image src={preview} alt="" width={800} height={600} />
<div class="actions">
<button type="button">Show interactive map</button>
<a href={directions} rel="noopener" target="_blank">Open in Google Maps</a>
</div>
</map-facade>
<script>
class MapFacade extends HTMLElement {
connectedCallback() {
this.querySelector('button')?.addEventListener(
'click',
() => {
const iframe = document.createElement('iframe');
iframe.src = this.dataset.src!;
iframe.title = this.dataset.title!;
iframe.allowFullscreen = true;
iframe.referrerPolicy = 'no-referrer-when-downgrade';
this.replaceChildren(iframe);
},
{ once: true },
);
}
}
if (!customElements.get('map-facade')) customElements.define('map-facade', MapFacade);
</script>
<style>
map-facade {
display: block;
position: relative;
aspect-ratio: 4 / 3;
overflow: hidden;
}
map-facade img,
map-facade :global(iframe) {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: cover;
border: 0;
}
.actions {
position: absolute;
bottom: 1rem;
left: 1rem;
display: flex;
gap: 0.5rem;
}
</style>
---
// src/pages/contact.astro
import MapFacade from '../components/MapFacade.astro';
import mapPreview from '../assets/map-preview.png';
---
<MapFacade
embedSrc="https://www.google.com/maps/embed?pb=..."
title="Map of our Springfield office"
preview={mapPreview}
directions="https://www.google.com/maps/dir/?api=1&destination=412+Mill+Road+Springfield+IL"
/>
For the preview image, use something you have rights to: a photo of the storefront, a simple illustrated location graphic, or an image from the Maps Static API (https://maps.googleapis.com/maps/api/staticmap?center=...&zoom=15&size=800x600&markers=...&key=...), which is a billed API with its own usage terms. The “Open in Google Maps” link keeps the component useful without JavaScript. The same facade pattern is explained in more detail in our YouTube embeds guide.
A lighter interactive map with Leaflet
When you need your own markers, several locations or custom styling, Leaflet is a small open-source mapping library that works with any tile provider. Load it only when the map scrolls into view:
npm install [email protected]
---
// src/components/LeafletMap.astro
interface Props {
lat: number;
lng: number;
label: string;
zoom?: number;
}
const { lat, lng, label, zoom = 15 } = Astro.props;
---
<leaflet-map data-lat={lat} data-lng={lng} data-label={label} data-zoom={zoom}>
<p>Loading map of {label}...</p>
</leaflet-map>
<script>
class LeafletMap extends HTMLElement {
connectedCallback() {
const observer = new IntersectionObserver(async ([entry]) => {
if (!entry.isIntersecting) return;
observer.disconnect();
const L = await import('leaflet');
await import('leaflet/dist/leaflet.css');
const { lat, lng, label, zoom } = this.dataset;
const point: [number, number] = [Number(lat), Number(lng)];
this.replaceChildren();
const map = L.map(this).setView(point, Number(zoom));
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© OpenStreetMap contributors',
}).addTo(map);
L.marker(point).addTo(map).bindPopup(label!);
}, { rootMargin: '200px' });
observer.observe(this);
}
}
if (!customElements.get('leaflet-map')) customElements.define('leaflet-map', LeafletMap);
</script>
<style>
leaflet-map {
display: block;
aspect-ratio: 4 / 3;
}
</style>
The dynamic import() means Vite splits Leaflet into its own chunk, so it downloads only when the map nears the viewport. Leaflet’s default marker icons sometimes fail to resolve after bundling; if markers show as broken images, set L.Icon.Default image paths or use a custom L.divIcon.
A note on tiles: the OpenStreetMap tile server is a volunteer-run service with a usage policy that rules out heavy or commercial traffic. For a production site, use a commercial tile provider that serves OpenStreetMap data (many have free tiers), and keep the attribution. MapLibre GL JS is another open-source option if you want vector tiles and smoother zooming, at a larger bundle size.
Measure the difference
Check what your map costs with PageSpeed Insights or the Lighthouse panel in Chrome DevTools before and after a change. Look at Total Blocking Time and the “Reduce the impact of third-party code” audit. A facade or directions link usually removes the map from that audit entirely. Our Core Web Vitals guide for Astro explains how each metric is affected by third-party embeds.
Location-heavy sites such as restaurants and property listings are where this matters most. The Real Estate and Food & Drink Komal theme categories include contact and location pages where any of these components can replace a default embed. For Astro-specific background on bundling client scripts, see Astro’s client-side scripts docs.
FAQ
How do I add Google Maps to an Astro site?
Copy the iframe from Google Maps’ Share, Embed a map option, paste it into an Astro component, and add loading="lazy". For a map near the top of the page, use a click-to-load facade instead, so the map loads only when a visitor asks for it.
Do I need an API key for Google Maps in Astro?
Not for the iframe from “Embed a map” or for Google Maps URLs that open search and directions. The Maps Embed API, the Maps Static API and the Maps JavaScript API all need a key from Google Cloud, which you should restrict to your domains.
Why does a Google Maps embed slow down my page?
The embed iframe loads Google’s map application, which includes a large amount of JavaScript, map tiles and fonts. On mobile that can add noticeable blocking time. Lazy loading, a facade or a simple directions link keeps that cost off the initial page load.
Is there a free alternative to Google Maps for Astro?
Leaflet is a free, open-source library that displays tiles from OpenStreetMap-based providers. The library itself is free, while tile hosting for a production site usually comes from a provider with a free tier. MapLibre GL JS is another open-source option for vector maps.
Can I show a map on a fully static Astro site?
Yes. Every option in this guide works on static output because the map loads in the visitor’s browser. No server or adapter is needed; only the API key restrictions and tile provider terms apply.