Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load google maps api using nextjs?

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

like image 368
grabury Avatar asked Jul 28 '26 10:07

grabury


1 Answers

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

  • Pass your API key to useLoadScript (a React hook provided by @react-google-maps/api that loads the Maps API)
  • Once loaded, return an instance of the GoogleMap component
    • In this simplified example, the initial location is memoized. But see the second example below for how you might use in conjunction with the Google Places API
    • You can optionally also add a Marker to the map
import { 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.

like image 62
warfield Avatar answered Aug 01 '26 09:08

warfield