CoolFace
Apppublic

im-amrith/crisp

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
geocoding.ts64 linesDownload Raw Back to utils
1// Cache for geocoding results2const geocodingCache = new Map<string, { lat: number; lon: number }>();3 4/**5 * Gets coordinates for a given place name using Nominatim API.6 * Results are cached to avoid repeated API calls.7 * @param placeName - The name of the place (e.g., "Siyana, Bulandshahar, Uttar Pradesh")8 * @returns The latitude and longitude, or null if not found.9 */10export const getCoordinates = async (placeName: string): Promise<{ lat: number; lon: number } | null> => {11  if (geocodingCache.has(placeName)) {12    return geocodingCache.get(placeName)!;13  }14 15  try {16    const url = `https://nominatim.openstreetmap.org/search`;17    const params = new URLSearchParams({18      q: placeName,19      format: 'json',20      limit: '1'21    });22    23    const response = await fetch(`${url}?${params.toString()}`);24    if (!response.ok) {25        throw new Error(`HTTP error! status: ${response.status}`);26    }27    const data = await response.json();28 29    if (data && data.length > 0) {30      const lat = parseFloat(data[0].lat);31      const lon = parseFloat(data[0].lon);32      const result = { lat, lon };33      geocodingCache.set(placeName, result);34      return result;35    } else {36      console.warn(`Could not find coordinates for '${placeName}'`);37      return null;38    }39  } catch (error) {40    console.error(`Error fetching coordinates for '${placeName}':`, error);41    return null;42  }43};44 45/**46 * Calculates the distance between two points using the Haversine formula.47 * @param lat1 Latitude of point 148 * @param lon1 Longitude of point 149 * @param lat2 Latitude of point 250 * @param lon2 Longitude of point 251 * @returns The distance in kilometers.52 */53export const calculateDistance = (lat1: number, lon1: number, lat2: number, lon2: number): number => {54  const R = 6371; // Radius of the Earth in km55  const dLat = (lat2 - lat1) * Math.PI / 180;56  const dLon = (lon2 - lon1) * Math.PI / 180;57  const a =58    Math.sin(dLat / 2) * Math.sin(dLat / 2) +59    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *60    Math.sin(dLon / 2) * Math.sin(dLon / 2);61  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));62  const distance = R * c;63  return distance;64};