React hook to get user's latitude and longitude.
Add the hook via the CLI:
npx @novajslabs/cli add useGeolocation
Or copy and paste the code into your project:
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 }
}
React 16.8 or higher
- Name
defaultPosition
- Type
- object
- Optional
- optional
- Description
Contains the initial latitude and longitude of the user.
- Name
defaultPosition.lat
- Type
- number
- Required
- required
- Description
The user's initial latitude.
- Name
defaultPosition.lng
- Type
- number
- Required
- required
- Description
The user's initial longitude.
- Name
isLoading
- Type
- boolean
- Description
Represents if the geolocation information is loading (true) or not (false).
- Name
position
- Type
- object
- Description
Contains the latitude and longitude of the user.
- Name
position.lat
- Type
- number
- Description
The user's latitude.
- Name
position.lng
- Type
- number
- Description
The user's longitude.
- Name
error
- Type
- string | null
- Description
Contains the error message in case it occurs.
- Name
getPosition
- Type
- function
- Description
Get the get user's latitude and longitude.
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
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