fastify-xgeocode
getLatLongByZip
Geocode a US ZIP code (5-digit or ZIP+4) to coordinates and address components via the Geocodio API.
getLatLongByZip
Geocode a US ZIP code to latitude/longitude and address components. Accepts standard 5-digit format ("10001") or ZIP+4 ("10001-1234").
Signature
fastify.xGeocode.getLatLongByZip(zipCode: string): Promise<GeoResult>
interface GeoResult {
zip: string
lat: number
lng: number
formatted_address: string | null
city: string | null
county: string | null
state: string | null
country: string | null
addressComponents: Record<string, string>
}
Params
| Name | Type | Required | Description |
|---|---|---|---|
zipCode | string | Yes | US ZIP code — 5 digits ("10001") or ZIP+4 ("10001-1234") |
Returns
A GeoResult object with coordinates and standardized address components from Geocodio.
Throws
| Error | When |
|---|---|
[xGeocode] Invalid input - zipCode must be a non-empty string | zipCode is null, undefined, or not a string |
[xGeocode] Invalid zip code format - must be 5 digits or 9 digits (ZIP+4) | Format doesn't match ^\d{5}(-\d{4})?$ |
[xGeocode] Geocoding API returned {status} | Geocodio returned a non-2xx HTTP status |
[xGeocode] No results found | Geocodio returned an empty results array |
Examples
Basic ZIP lookup
fastify.get("/location/:zip", async (request) => {
const result = await fastify.xGeocode.getLatLongByZip(request.params.zip);
return result;
});
// GET /location/10001
// {
// zip: "10001",
// lat: 40.7484,
// lng: -73.9967,
// formatted_address: "New York, NY 10001",
// city: "New York",
// county: "New York County",
// state: "NY",
// country: "US",
// addressComponents: { ... }
// }
Store locator — find nearest store to a ZIP
fastify.post("/stores/nearest", async (request, reply) => {
const { zipCode } = request.body;
const { lat, lng } = await fastify.xGeocode.getLatLongByZip(zipCode);
const stores = await fastify.prisma.store.findMany();
const ranked = stores
.map((store) => ({
...store,
distance: fastify.xGeocode.getDistance(lat, lng, store.lat, store.lng),
}))
.sort((a, b) => a.distance.miles - b.distance.miles);
return { nearestStore: ranked[0] };
});
See Also
- getLatLongByAddress — Full street address geocoding
- getDistance — Calculate distance between two coordinates
- batchGeocode — Geocode multiple ZIPs/addresses at once
AI Context
package: "@xenterprises/fastify-xgeocode"
method: fastify.xGeocode.getLatLongByZip(zipCode)
use-when: Geocode a US zip code (NNNNN or NNNNN-NNNN) to coordinates and address components via Geocodio
returns: { lat, lng, formatted_address, components }
