DEV Community

Cover image for Know your users' location in React Ts
Dhruv Singh
Dhruv Singh

Posted on

Know your users' location in React Ts

In this post you will see how to get user location who landed on your website.

Note: It will only work when the user give their consent to share location which is by default asked by the browser.

Library used:

  • react-geolocated: To get user location.
  • firebase: To save user location in firestore.

Setup FireBase
On the dashboard of your firebase project Select the type of project here in our case it is Web.

Image description

Continue the project setup. Here these are the configs that you need to use in your react project to access firebase.

Image description

Create a config for firebase.

import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
import { getFirestore } from "firebase/firestore";

const firebaseConfig = {
  apiKey: "AIzaXXXXXXXXXXXXXXXX-XXXXXXMCQA",
  authDomain: "projectId.firebaseapp.com",
  projectId: "projectId",
  storageBucket: "projectId.appspot.com",
  messagingSenderId: "12XXXXXXX12",
  appId: "1:XXXXXXXXX:web:XXXXXXXXXXXXXXXXXXX",
  measurementId: "G-XXXXXXXXXX",
};

const app = initializeApp(firebaseConfig);
let analytics;
if (app.name && typeof window !== 'undefined') {
    analytics = getAnalytics(app);
  }
const db = getFirestore(app);
export { db };
Enter fullscreen mode Exit fullscreen mode

Get user Location
Here ddDoc(collection(db, "location"), location is the db name.

import React, { FC, useEffect } from "react";
import Image from "next/image";
import Header from "../components/Header";
import { Box } from "@mui/material";
import { useGeolocated } from "react-geolocated";
import { db } from "../config/firebase";
import { collection, addDoc, Timestamp } from "firebase/firestore";

type Location = {
  accuracy: number | null;
  altitude: number | null;
  altitudeAccuracy: number | null;
  heading: number | null;
  latitude: number | null;
  longitude: number | null;
  speed: number | null;
};
type typeChildren = {
  children: React.ReactNode;
};

const Layout: FC<typeChildren> = ({ children }) => {
// initiate geolocation
  const { coords } = useGeolocated({
    positionOptions: {
      enableHighAccuracy: true,
    },
    userDecisionTimeout: 5000,
  });
// to save location in fireStore
  const saveLocation = async (loc: Location) => {
    try {
      await addDoc(collection(db, "location"), {
        latitude: loc.latitude,
        longitude: loc.longitude,
        accuracy: loc.accuracy,
        altitude: loc.altitude,
        altitudeAccuracy: loc.altitudeAccuracy,
        heading: loc.heading,
        created: Timestamp.now(),
      });
    } catch (err) {
      console.log(err);
    }
  };

  useEffect(() => {
    if (!!coords?.latitude) {
      saveLocation(coords);
    }
  }, [coords]);

  return (
    <>
      <Image
        src="/emojiImg.png"
        layout="fill"
        alt="emoji"
      />
      <Header />
      <Box>{children}</Box>
    </>
  );
};`
Enter fullscreen mode Exit fullscreen mode

Result
You will be able to see the location of your user.

Image description

Top comments (0)