Skip to content

useGeolocation

React hook to get user's latitude and longitude.

Add the hook via the CLI:

sh
npx @novajslabs/cli add useGeolocation
sh
npx @novajslabs/cli add useGeolocation
sh
pnpm dlx @novajslabs/cli add useGeolocation

Or copy and paste the code into your project:

ts
import { useState } from "react";

interface Payload {
  lat: number;
  lng: number;
}

export function useGeolocation(defaultPosition: Payload | null = null) {
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [position, setPosition] = useState<Payload | null>(defaultPosition);
  const [error, setError] = useState<string | null>(null);

  function getPosition(): void {
    if (!navigator.geolocation)
      return setError("Your browser does not support geolocation");

    setIsLoading(true);
    navigator.geolocation.getCurrentPosition(
      (pos) => {
        setPosition({
          lat: pos.coords.latitude,
          lng: pos.coords.longitude,
        });
        setIsLoading(false);
      },
      (error) => {
        setError(error.message);
        setIsLoading(false);
      }
    );
  }

  return { isLoading, position, error, getPosition };
}
js
import { useState } from "react";

export function useGeolocation(defaultPosition = null) {
  const [isLoading, setIsLoading] = useState(false);
  const [position, setPosition] = useState(defaultPosition);
  const [error, setError] = useState(null);

  function getPosition() {
    if (!navigator.geolocation)
      return setError("Your browser does not support geolocation");

    setIsLoading(true);
    navigator.geolocation.getCurrentPosition(
      (pos) => {
        setPosition({
          lat: pos.coords.latitude,
          lng: pos.coords.longitude,
        });
        setIsLoading(false);
      },
      (error) => {
        setError(error.message);
        setIsLoading(false);
      }
    );
  }

  return { isLoading, position, error, getPosition };
}

Requirements

React 16.8 or higher

Parameters

defaultPosition

Type: object

Contains the initial latitude and longitude of the user.

defaultPosition.lat required

Type: number

The user's initial latitude.

defaultPosition.lng required

Type: number

The user's initial longitude.

Return values

isLoading

Type: boolean

Represents if the geolocation information is loading (true) or not (false).

position

Type: object

Contains the latitude and longitude of the user.

position.lat

Type: number

The user's latitude.

position.lng

Type: number

The user's longitude.

error

Type: string | null

Contains the error message in case it occurs.

getPosition

Type: function

Get the user's latitude and longitude.

Example

tsx
import { useEffect } from "react";
import { useGeolocation } from "./hooks/useGeolocation";

const App = () => {
  const { isLoading, position, error, getPosition } = useGeolocation();

  useEffect(() => {
    getPosition();
  }, []);

  return (
    <div>
      {isLoading && <p>Loading...</p>}
      {error && <p>Error: {error}</p>}
      {position && (
        <p>
          Your current position is: latitude {position.lat}, longitude{" "}
          {position.lng}
        </p>
      )}
    </div>
  );
};

export default App;

Use cases

Here are some use cases where this React hook is useful:

  • Integrating location-based services such as mapping or navigation functionalities in a web application
  • Developing a weather forecast application that fetches the user's current location to provide localized weather information
  • Creating a geotagging feature for user-generated content in a social media platform
  • Enhancing user experience by providing location-based recommendations or suggestions in an e-commerce website