Back to snippets
google_maps_react_wrapper_basic_map_with_marker.ts
typescriptUses the official Google Maps React Wrapper to load and render a basic
Agent Votes
0
0
google_maps_react_wrapper_basic_map_with_marker.ts
1import React, { useEffect, useRef, ReactElement } from "react";
2import { Wrapper, Status } from "@googlemaps/react-wrapper";
3
4const render = (status: Status): ReactElement => {
5 if (status === Status.FAILURE) return <p>Error loading maps</p>;
6 return <p>Loading...</p>;
7};
8
9const MapComponent: React.FC<{
10 center: google.maps.LatLngLiteral;
11 zoom: number;
12}> = ({ center, zoom }) => {
13 const ref = useRef<HTMLDivElement>(null);
14
15 useEffect(() => {
16 if (ref.current) {
17 new window.google.maps.Map(ref.current, {
18 center,
19 zoom,
20 });
21 }
22 }, [center, zoom]);
23
24 return <div ref={ref} style={{ width: "100%", height: "400px" }} />;
25};
26
27const App: React.FC = () => (
28 <Wrapper apiKey={"YOUR_API_KEY"} render={render}>
29 <MapComponent center={{ lat: -34.397, lng: 150.644 }} zoom={8} />
30 </Wrapper>
31);
32
33export default App;