How do you load and use the google maps api using Nextjs?
1 - How do you load the api? I've tried to load it in _document.js:
import { Html, Head, Main, NextScript } from 'next/document'
import Script from 'next/script'
const source = `https://maps.googleapis.com/maps/api/js?key=${process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY}&libraries=places`
const Document = () => {
return (
<Html>
<Head>
<Script type="text/javascript" src={source} strategy="beforeInteractive" />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
export default Document
2 - How do you reference the API?
Something like: ? window.google.maps.places.AutocompleteService().getPlacePredictions()
But I get an error that google is undefined
I have also tried using npm libraries but none seem to work. react-places-autocomplete use-places-autocomplete
The Google Maps team provides a quick, helpful tutorial "How to load Maps JavaScript API in React" that uses the @react-google-maps/api package in a Next.js project. The code snippet below comes from the repo linked by the tutorial's author, @leighhalliday.
1. How to load the Google Maps JavaScript API
Marker to the mapimport { useMemo } from "react";
import { GoogleMap, useLoadScript, Marker } from "@react-google-maps/api";
export default function Home() {
const { isLoaded } = useLoadScript({
googleMapsApiKey: process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY,
});
if (!isLoaded) return <div>Loading...</div>;
return <Map />;
}
function Map() {
const center = useMemo(() => ({ lat: 44, lng: -80 }), []);
return (
<GoogleMap zoom={10} center={center} mapContainerClassName="map-container">
<Marker position={center} />
</GoogleMap>
);
}
2. How to add Autocomplete with the Places + Google Maps API's
The Google Maps team provide a second tutorial to implement search + autocomplete in your map that leverages the use-places-autocomplete package. You can also find the full code in @leighhalliday's repo example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With