useGeolocation
The useGeolocation
hook allows you to easily track the user's current location using the browser's geolocation API. It returns an object containing the current latitude, longitude, and an optional error message if any issues arise during the geolocation retrieval process.
Installation
-
Make sure you have
@ridgehkr/useful
installed in your application. If not, you can get started by following the installation instructions. -
Import
useGeolocation
into your component.
import { useGeolocation } from '@ridgehkr/useful'
Example
The following is a basic example where useGeolocation
is used to query the browser's location API and display the user's latitude and longitude. The getLocation
function is used to trigger the location retrieval process, and the location
object contains the current latitude, longitude, and any error messages.
import { useGeolocation } from '@ridgehkr/useful'
function LocationComponent() {
const { location, getLocation } = useGeolocation()
// Trigger getLocation to update the user's location
const handleButtonClick = () => {
getLocation()
}
return (
<div>
<p>Latitude: {location.latitude}</p>
<p>Longitude: {location.longitude}</p>
{location.error && <p>Error: {location.error}</p>}
<button onClick={handleButtonClick}>Get Location</button>
</div>
)
}
API Reference
Hook Signature
useGeolocation(): GeoLocationState
Parameters
useGeolocation
does not accept any parameters.
Return Value
useGeolocation
returns a GeoLocationState
object with the following properties:
Property | Type | Description |
---|---|---|
location | GeoLocation | The user's location details, or an error message if they could not be retrieved |
getLocation | () => void | A function to trigger the location retrieval process |
GeoLocation
Type
Property | Type | Description |
---|---|---|
latitude | number | The user's current latitude |
longitude | number | The user's current longitude |
error | string | An error message if retrieval fails |