useGeolocation

About

A hook to provide the geolocation info on client side.

Examples

Getting geolocation in a component

import { useGeolocation } from "rooks";
import React from "react";
import { useState } from "react";

function App() {
  const geoObj = useGeolocation();

  return (
    <div
      className="App"
      style={{
        display: "flex",
        alignItems: "center",
        flexDirection: "column",
      }}
    >
      <h1>Rooks : useGeolocation Example</h1>
      <p>{geoObj && JSON.stringify(geoObj)}</p>
    </div>
  );
}

export default App;

Getting geolocation in a component on some condition

import { useGeolocation } from "rooks";
import React from "react";
import { useState } from "react";

export default function App() {
  const [when, setWhen] = React.useState(false);

  const geoObj = useGeolocation({
    when,
  });

  return (
    <div
      className="App"
      style={{
        display: "flex",
        alignItems: "center",
        flexDirection: "column",
      }}
    >
      <h1>Rooks : useGeolocation Example</h1>
      <p>Check out console</p>

      <div
        style={{
          display: "flex",
          alignItems: "center",
          flexDirection: "column",
        }}
      >
        <button
          onClick={() => {
            setWhen(true);
          }}
        >
          Get Geolocation
        </button>
        <p>{geoObj && JSON.stringify(geoObj)}</p>
      </div>
    </div>
  );
}

Arguments

The argument is an object with the following optional items:

Argument valueTypeDescription
options.enableHighAccuracybooleanenable high accuracy if true
options.timeoutnumbertimeout in milliseconds
options.maximumAgenumbermaximumAge in milliseconds
options.whenbooleanthis hook will run when when is true

Returns

Returns an object with following items:

{
lat?: number;
lng?: number;
isError: boolean;
message: string;
}

Join the community!

Join our discord server! You can click the floating discord icon at the bottom right of the screen and chat with us!

Powered by vercel