Getting started
Install the package, get an API key and render your first markers.
Install
npm i google-maps-react-markersThe package ships TypeScript types and depends on @types/google.maps, so google.maps.* types work out of the box.
Get an API key
- Create a key in the Google Cloud console and enable the Maps JavaScript API.
- Restrict it to your sites with HTTP referrers (for example
https://example.com/*). A browser key is always visible in the page: the restriction is what protects it. - For advanced markers, create a map ID in Map management. While you try things out,
DEMO_MAP_IDworks.
Your first map
import { GoogleMap, Marker } from 'google-maps-react-markers'
const stores = [
{ id: 'venice', name: 'Venice', lat: 45.4408, lng: 12.3155 },
{ id: 'milan', name: 'Milan', lat: 45.4642, lng: 9.19 },
]
export function StoreMap() {
return (
<GoogleMap
apiKey="YOUR_API_KEY"
mapId="DEMO_MAP_ID"
defaultCenter={{ lat: 45.4, lng: 11 }}
defaultZoom={7}
style={{ height: 480 }}
>
{stores.map((store) => (
<Marker key={store.id} lat={store.lat} lng={store.lng} anchor="bottom">
<div className="price-tag">{store.name}</div>
</Marker>
))}
</GoogleMap>
)
}Give the map a height
Without a className, <GoogleMap> fills its parent (width: 100%, height: 100%): if the parent has no height, neither does the map. With a className, the class sets the size. style works in both cases.
What happens
- On the server, and until the API is ready,
<GoogleMap>renders its container andloadingContent. Markers render nothing yet. - In the browser it loads the Maps JavaScript API once, with your
apiKey,language,regionandlibraries. - It creates the map with
defaultCenter,defaultZoom,mapIdandoptions, then callsonLoad. - Each
<Marker>creates its marker once and renders its children into it with a React portal.
Next steps
- Markers: anchor, stacking, clicks.
- Events and camera:
onChange, map events, controlledcenterandzoom. - Next.js: Server Components and static export.