useGeocode
This hook provides geocoding functionality to convert addresses into geographic coordinates (latitude and longitude). It's perfect for location-based widgets that need to convert user-friendly addresses into precise coordinates for mapping, weather data, or location services.
Import
import { useGeocode } from "~lib/geocoding";
API
const geocodeData = useGeocode(address);
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
address | string | Yes | The address string to geocode (e.g., "New York, NY, US") |
Return Value
The hook returns GeocodeResult | undefined. The result is undefined while loading.
| Name | Type | Description |
|---|---|---|
state | string | State or region name |
name | string | Location name |
lat | number | Latitude coordinate |
lon | number | Longitude coordinate |
country | string | Country code |
error | { message: string } | Error object, present if the geocoding failed |
Examples
Basic Address Geocoding
import { useGeocode } from "~lib/geocoding";
export const Widget = () => {
const geocodeData = useGeocode("San Francisco, CA, US");
if (!geocodeData) {
return <div>Loading location data...</div>;
}
return (
<div>
<h2>{geocodeData.name}</h2>
<p>Country: {geocodeData.country}</p>
<p>State: {geocodeData.state}</p>
<p>
Coordinates: {geocodeData.lat}, {geocodeData.lon}
</p>
</div>
);
};
With Error Handling
import { useGeocode } from "~lib/geocoding";
export const Widget = () => {
const geocodeData = useGeocode("New York, NY, US");
if (!geocodeData) {
return <div>Loading location data...</div>;
}
if (geocodeData.error) {
return <div>Geocoding failed: {geocodeData.error.message}</div>;
}
return (
<div>
<h2>
{geocodeData.name}, {geocodeData.state}
</h2>
<p>
Coordinates: {geocodeData.lat}, {geocodeData.lon}
</p>
</div>
);
};
Address Format Guidelines
For best results, format your addresses using the following patterns:
- City, State, Country:
"New York, NY, US" - City, Country:
"London, UK" - Full Address:
"1600 Amphitheatre Parkway, Mountain View, CA, US" - Postal Code:
"10001, US"
The API supports various address formats, but more specific addresses generally yield more accurate results.
See Also
- useFetch - The underlying hook used for HTTP requests
- useResource - For loading async resources with caching support