Iirolta saatu
This commit is contained in:
33
src/utils.ts
Normal file
33
src/utils.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
export function haversineDistance(lat1: number, lon1: number, lat2: number, lon2: number): number {
|
||||
const R = 6371e3; // Earth radius in meters
|
||||
const φ1 = (lat1 * Math.PI) / 180;
|
||||
const φ2 = (lat2 * Math.PI) / 180;
|
||||
const Δφ = ((lat2 - lat1) * Math.PI) / 180;
|
||||
const Δλ = ((lon2 - lon1) * Math.PI) / 180;
|
||||
|
||||
const a =
|
||||
Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
|
||||
Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
|
||||
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
||||
|
||||
return R * c; // Distance in meters
|
||||
}
|
||||
|
||||
export async function reverseGeocode(lat: number, lon: number): Promise<string | undefined> {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lon}&zoom=14&addressdetails=1`,
|
||||
{
|
||||
headers: {
|
||||
'Accept-Language': 'en,fi'
|
||||
}
|
||||
}
|
||||
);
|
||||
if (!response.ok) return undefined;
|
||||
const data = await response.json();
|
||||
return data.display_name || data.name || undefined;
|
||||
} catch (error) {
|
||||
console.error('Geocoding failed:', error);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user