DEV Community

jss475
jss475

Posted on

Google Maps with React

Today I'll be showing you how I used Google Maps with react to create a dynamic map on a webpage.

The first thing you need to do is install this package:
npm i @react-google-maps/api

More information on this can be found here: https://www.npmjs.com/package/@react-google-maps/api

Sometimes you may have to end --legacy-peer-deps at the end of npm install. You can read more about that on google/stackoverflow.

Once you've installed the package:
Let's say I'm in my React component

I'm going to first import the below:

import {GoogleMap, useLoadScript, Marker} from "@react-google-maps/api"

Then, I will need the following code
const {isLoaded} = useLoadScript({googleMapsApiKey: process.env.REACT_APP_NEXT_PUBLIC_GOOGLE_MAPS_API_KEY})

What this piece of code here is we use the useLoadScript hook to load in our Google Maps API key. Once that's loaded, isLoaded is a truthy value. You can read more about how to create a Google Maps API key on Google's official documentation. The process.env portion here is referencing a .env.local file that has REACT_APP_NEXT_PUBLIC_GOOGLE_MAPS_API_KEY = YOUR_API_KEY. The reason we do this is to ensure our API key is hidden. Just make sure you don't push the .env.local file to Github!!!!

The next piece of code is where we make the map itself:

//creating the google map
    //here i'm just initializing a variable called map that will hold the Google Map instance
    let map
    //if our useLoadScript hasn't completed, return "Loading..."
    if(!isLoaded){
        map = <div>Loading...</div>
    //if it is loaded, create the map
    }else{
        map = <GoogleMap zoom={13} center={{lat: YOUR_LATITUDE, lng: YOUR_LONGITUDE}} mapContainerClassName="map-container">

            <Marker position={{lat: YOUR_LATITUDE, lng: YOUR_LONGITUDE}} label="SL"  />
        </GoogleMap>
    }

return (
     <>
          {map}
     </>
)
Enter fullscreen mode Exit fullscreen mode

The zoom on GoogleMap is just how far zoomed you are in on the map when it renders on the webpage. You can experiment with what you like! The center takes in a lat, lng of where you want the center of your map to be. I also added a marker on the map at the center location here!

Below is what you should see!
Image description

Top comments (1)

Collapse
 
lico profile image
SeongKuk Han

It looks easy to use :)