use-geolocation (use-geolocation)
Enter and exit fullscreen mode for a given element or the entire page.
v0.1.0
Usage
import { use-geolocation } from "@/hooks"
1"use client";
2
3import React from "react";
4
5import { Button } from "@/components/ui/button";
6import {
7 Card,
8 CardContent,
9 CardDescription,
10 CardFooter,
11 CardHeader,
12 CardTitle,
13} from "@/components/ui/card";
14
15import { useGeolocation } from "@/components/hooks/use-geolocation";
16
17export function UseGeolocationDemo() {
18 const { position, error, isLoading, clearWatch } = useGeolocation();
19
20 return (
21 <Card className="relative max-w-sm w-full">
22 <CardHeader>
23 <CardTitle>useGeolocation</CardTitle>
24 <CardDescription>
25 Declarative Geolocation API hook demo.
26 </CardDescription>
27 </CardHeader>
28 <CardContent className="space-y-4">
29 {isLoading && <p>Loading...</p>}
30 {error && <p className="text-red-500">{error.message}</p>}
31 {position && (
32 <div>
33 <p>Latitude: {position.coords.latitude}</p>
34 <p>Longitude: {position.coords.longitude}</p>
35 </div>
36 )}
37 </CardContent>
38 <CardFooter className="flex gap-2">
39 <Button onClick={clearWatch}>Clear Watch</Button>
40 </CardFooter>
41 </Card>
42 );
43}
44
Install
npx wkkkis-hooks add use-geolocation
Options
Name | Type | Default | Description |
---|---|---|---|
options | PositionOptions | {} | Options for getCurrentPosition and watchPosition |
Features
- Declarative interface for both getCurrentPosition and continuous watchPosition .
- Automatic cleanup on component unmount.
- Graceful fallback if Geolocation API is not supported.
- Fully typed with TypeScript.
Browser Support
- Chrome: Supported (since v5)
- Firefox: Supported (since v3.5)
- Safari: Supported (since 5)
- Edge: Supported
- Opera: Supported
Security Considerations
- Requires secure context (HTTPS).
- User permission prompt is shown on first request.
Best Practices & Caveats
- Always handle the error case to inform the user.
- Clear the watch when no longer needed to save battery.
- Consider asking permission only when necessary.
- For frequent updates, throttle or debounce updates to avoid performance issues.
- Use maximumAge and timeout options wisely.
Files in this hook
Source | Destination |
---|---|
files/use-geolocation.ts | src/hooks/use-geolocation.ts |