Browser APIs
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 value | Type | Description |
|---|---|---|
| options.enableHighAccuracy | boolean | enable high accuracy if true |
| options.timeout | number | timeout in milliseconds |
| options.maximumAge | number | maximumAge in milliseconds |
| options.when | boolean | this hook will run when when is true |
Returns
Returns an object with following items:
{
lat?: number;
lng?: number;
isError: boolean;
message: string;
}