fastify-xgeocode
getDistance
Calculate the distance between two geographic coordinates using the Haversine formula — no API call required.
getDistance
Calculates the great-circle distance between two geographic coordinates using the Haversine formula. This is a purely local computation — no network call is made.
Signature
fastify.xGeocode.getDistance(
lat1: number,
lng1: number,
lat2: number,
lng2: number
): { kilometers: number; miles: number; meters: number }
Params
| Name | Type | Required | Description |
|---|---|---|---|
lat1 | number | Yes | Origin latitude (-90 to 90) |
lng1 | number | Yes | Origin longitude (-180 to 180) |
lat2 | number | Yes | Destination latitude (-90 to 90) |
lng2 | number | Yes | Destination longitude (-180 to 180) |
Returns
{
kilometers: number, // rounded to 2 decimal places
miles: number, // rounded to 2 decimal places
meters: number // rounded to nearest meter
}
Throws
[xGeocode] Invalid coordinates - latitude and longitude must be numbers— non-numeric input[xGeocode] Invalid latitude - must be between -90 and 90[xGeocode] Invalid longitude - must be between -180 and 180
Examples
Distance between two known coordinates
const dist = fastify.xGeocode.getDistance(
34.0522, -118.2437, // Los Angeles
40.7128, -74.0060 // New York
);
// { kilometers: 3940.07, miles: 2448.05, meters: 3940074 }
Find nearby users within 50 miles
fastify.get("/api/users/nearby", async (request) => {
const { lat, lng } = request.query;
const users = await db.user.findMany({ where: { lat: { not: null } } });
return users
.map((user) => ({
...user,
distance: fastify.xGeocode.getDistance(
Number(lat), Number(lng),
user.lat, user.lng
),
}))
.filter((u) => u.distance.miles <= 50)
.sort((a, b) => a.distance.miles - b.distance.miles);
});
See Also
- getLatLongByZip(zipCode) — get coordinates from a zip code
- getLatLongByAddress(address) — get coordinates from an address
AI Context
package: "@xenterprises/fastify-xgeocode"
method: fastify.xGeocode.getDistance(lat1, lng1, lat2, lng2)
use-when: Calculate the distance between two coordinate pairs using the Haversine formula — no API call
returns: { miles, kilometers }
