Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 5675

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 27, 20242024-11-27T11:29:08+00:00 2024-11-27T11:29:08+00:00

Adding Google Maps to the Keith Lee food app (React.js)

  • 60k

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

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

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
The Open Source Firebase Alternative | Supabase

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

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

Fill out the form and click Create.

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

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

Click Credentials on the left hand side.

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.

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

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> 
Enter fullscreen mode Exit fullscreen mode

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; 
Enter fullscreen mode Exit fullscreen mode

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

    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);           });       }, []); 
Enter fullscreen mode Exit fullscreen mode

  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

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**

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

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

googlemapsjavascriptreactwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.