Look up a place from an address
Many APIs, such as weather and maps, want a latitude and longitude, but people know their location as an address. The useGeocode hook turns one into the other.
import { useGeocode } from "~lib/geocoding";
export 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;
};
export 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 Widget's settings.
</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.
See useGeocode in the reference for everything it returns.