Adding Google Maps to the Keith Lee food app (React.js)
Tags: react, googlemaps, javascript, webdev
Published: 2023-04-02 02:03:55


![](https://cdn-images-1.medium.com/max/2000/1*PY4ZtSzNZqfG9vfVTJ9yNw.png)

In the previous article, I wrote about creating a Keith Lee food app using React.js and Firebase.
[**Creating a Keith Lee Food App w/ React.js & ChatGPT**](https://cmcoffee.dev/creating-a-keith-lee-food-app-w-react-js-chatgpt-11ac5ee67b8c)

In this article, I will show you how I used the Google Maps Javascript SDK to display the list of restaurants on a map.
[**Google Maps Platform Documentation | Maps JavaScript API | Google Developers**](https://developers.google.com/maps/documentation/javascript)

I have discontinued using Firebase and moved to Netlify for hosting and Supabase for the backend. I will create an article on my steps to migrate away from Firebase to Supabase.
[**Develop and deploy websites and apps in record time | Netlify**](https://www.netlify.com/)
[**The Open Source Firebase Alternative | Supabase**](https://supabase.com/)

### Enabling the Google Maps Javascript SDK

We are going to follow along with the documentation from Google.
[**Set up your Google Cloud project | Maps JavaScript API | Google Developers**](https://developers.google.com/maps/documentation/javascript/cloud-setup)

Create a Google Project. Click on the blue **Create new project** button.

![](https://cdn-images-1.medium.com/max/3488/1*GIpnzZEgrvdyq13eRawMVQ.png)

Fill out the form and click **Create**.

![](https://cdn-images-1.medium.com/max/2252/1*ztzon1O68JPuJ54rEYZ8UA.png)

Now we need to enable Google Maps for our project. Go to the following link and click **Enable the Maps Javascript API**
[**Set up your Google Cloud project | Maps JavaScript API | Google Developers**](https://developers.google.com/maps/documentation/javascript/cloud-setup#enabling-apis)

![](https://cdn-images-1.medium.com/max/3752/1*V2XMu8_jUBnDm6Ac7Fnr7g.png)

The button below will initially state **Enable**. Click it then it will say **Manage. **Now click **Manage**

![](https://cdn-images-1.medium.com/max/2000/1*bZwVm1xBV0B2kQswdyASTg.png)

Click Credentials on the left hand side.

![](https://cdn-images-1.medium.com/max/2000/1*zGgJWtLVQrSc40TC2v29dA.png)

You will see your Google Maps API key. We will need this soon. You may also restrict the API key to localhost:3000. When you get a domain, you may add it to the list.

![](https://cdn-images-1.medium.com/max/4288/1*6kcESUDS91l958Kww_8vIg.png)

We will first need to load the Javascript API in our React project. Go to the following link. We will follow along with this documentation.
[**Load the Maps JavaScript API | Google Developers**](https://developers.google.com/maps/documentation/javascript/load-maps-js-api)

I am going to use the recommended Dynamic Library Import. Add the following Javascript code before the closing body tag in index.html

    <script>
      (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src='https://maps.${c}apis.com/maps/api/js?'+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
        key: "YOUR_API_KEY_HERE",
        v: "weekly",
        libraries: ["marker", "maps"]
        // Add other bootstrap parameters as needed, using camel case.
        // Use the 'v' parameter to indicate the version to load (alpha, beta, weekly, etc.)
      });
    </script>

Notice we are adding the **marker** and **maps** libraries. Make sure to add your API key here.

Now let’s create a new React functional component. We can also copy the firebase code from the previous article.
```
    import {Box} from "@mui/material";
    
    
    const config = {
      // Your Firebase project's config object goes here
    };
    
    firebase.initializeApp(config);
    const db = firebase.firestore();
    
    const RestaurantMap = () => {
    
    
    
    
        return <Box
            sx={{
                height: '100vh',
                width: '100%'
            }}
            id="map"
        >
    
        </Box>
    
    
    }
    
    export default RestaurantMap;
```
You can run the code and it will show a blank Google map.

You can run the code and it will show a blank Google map.

We will then load the markers on the google map. Add this right above the return. Note I have comments of numbers. I will detail those steps under the code.

Also, we are querying firebase again. We could use redux-toolkit to load and save the data only when needed. For now, we will load it again. In the future, I may add redux-toolkit. It would only take a few mins to implement.
[**Quick Start | Redux Toolkit**](https://redux-toolkit.js.org/tutorials/quick-start)
```
    useEffect(() => {
        // Get data from the 'tiktoks' collection in Firestore
       const google = window.google; // 1
       const {Map} = await google.maps.importLibrary("maps"); // 2
       const map = new Map(document.getElementById("map"), {  
                        center: {lat: 36.188110, lng: -115.176468},
                        zoom: 12,
                   });
       db.collection('tiktoks').get() // 3
          .then(snapshot => {
                const data = snapshot.docs.map(doc => doc.data()); // Each item in firebase
            
                const position = {lat: place.lat, lng: place.lng};
                
    
                const marker = new google.maps.Marker({ // 4
                     map: map,
                     position: position,
                     title: place.name,
                });
    
                // ...Retrieve variables below depending on what you want to do 
    
                const information = new google.maps.InfoWindow({ // 5
                    content: '
                             <h4>${place.name}</h4>
                             <div>
                                 ${address}
                             </div>
                             ${dir}
                             ${callDiv}
                             <hr>
                             <div>
                                 <a href="${shareHref}" target="_blank"/>Share</a>
                             </div>
                             <hr>
                              <div>
                                 <a href="${tiktokUrl}" target="_blank"/>Watch Review</a>
                             </div>
                             ${orderUrl}
                             '
                });
    
                marker.addListener('click', function () { // 6
                    information.open(map, marker);
                });
    
    
    
          })
          .catch(error => {
            console.log(error);
          });
      }, []);
```

 1. Add the google library

 2. Import the maps library from google and create Map object. I have this centered in Las Vegas, since this is where most of the food reviews happen.

 3. Get the list of items from firebase

 4. Add the Google Marker for the current item

 5. Add the InfoWindow to the Google Marker. This is the popup that shows when you click the Google Marker.

 6. Add a click listener to the marker to make the InfoWindow popup when you show it.

You can refer to the documentation for further customization:
[**Add a Google Map with a Marker to Your Website | Maps JavaScript API | Google Developers**](https://developers.google.com/maps/documentation/javascript/adding-a-google-map)

A few days after creating this map with the list of items, I found someone created a Google MyMaps on reddit.

![**Reddit Keith Lee map**](https://www.reddit.com/r/vegaslocals/comments/10pqllx/i_made_a_google_map_of_the_places_keith_lee_has/)

I liked it so much, I decided to add it to the web app on a separate page

![](https://cdn-images-1.medium.com/max/2000/1*-eINJsjyJIvlOta_39_E5g.png)

Thanks for reading. Let me know if any clarification is needed. You can find the Keith Lee food app at the following link:
[**Keith Lee Food Reviews**](https://keithleefood.com/)