Geocoding
Many APIs, such as weather and maps, want a latitude and longitude, but people know their location as an address. The useGeocode hook from the Blotch Library turns one into the other.
import { useGeocode } from "~lib/geocoding";
const Widget = () => {
const { data: place } = useGeocode("London, UK");
return (
<div>
{place.name}: {place.lat}, {place.lon}
</div>
);
};
Like useFetch, your Widget waits for the result before it is drawn, so data is always there.
Pairing it with an Input
Let the person installing your Widget type their location into an Address Input or a text Input. Read it with useInputs, geocode it and pass the coordinates on to the API you need:
import { useFetch } from "~lib/use-fetch";
import { useGeocode } from "~lib/geocoding";
import { useInputs } from "~lib/use-inputs";
type Forecast = {
readonly temperature: number;
};
const Widget = () => {
const { LOCATION } = useInputs();
const { data: place } = useGeocode(LOCATION);
const { data: forecast } = useFetch<Forecast>(
`https://api.example.com/forecast?lat=${place.lat}&lon=${place.lon}`,
);
return (
<div>
<h2>{place.name}</h2>
<p className="text-6xl">{forecast.temperature}°C</p>
</div>
);
};
When the address can't be found
An address with no match still returns data, with an error.message describing the problem and placeholder values everywhere else. Check for it before using the coordinates:
const { data: place } = useGeocode(LOCATION);
if (place.error) {
return (
<div>Couldn't find "{LOCATION}". Check the address in the Console.</div>
);
}
Address formats
Addresses resolve most reliably in one of these forms:
| Format | Example |
|---|---|
| City, State, Country | "New York, NY, US" |
| City, Country | "London, UK" |
| Postal code, Country | "10001, US" |
Caching
Results are kept in the proxy cache, since an address rarely moves. Every Frame looking up the same address shares one result, so geocoding adds almost nothing to how long your Widget takes to prepare.
Reference
import { useGeocode } from "~lib/geocoding";
const { data } = useGeocode(address);
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
address | string | Yes | The address to look up. |
Returns
data has these properties:
| Property | Type | Description |
|---|---|---|
name | string | The full, formatted address that was matched. |
state | string | The state, province or region, abbreviated where there is one. |
country | string | The country code. |
lat | number | Latitude. |
lon | number | Longitude. |
error | { message: string } | undefined | Set when the address could not be found. |