Skip to content

Instantly share code, notes, and snippets.

@damianobarbati
Created December 2, 2024 13:25
Fn to geocode using OpenStreetMap
export const geocodeWithOSM = async (q: string): Promise<geocode_output | null> => {
await sleep(100); // prevent rate-limiting
// we need to send a user-agent header to prevent 403 errors from OSM
const headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36' };
const { data } = await axios.get(`https://nominatim.openstreetmap.org/search?q=${q}&addressdetails=1&limit=1&format=jsonv2`, { timeout: 20_000, headers });
const [resultItem] = data;
if (!resultItem?.address) return null;
const country_code = resultItem.address.country_code?.toUpperCase();
const formattedAddress = [`${resultItem.address.house_number || ''} ${resultItem.address.road || ''}`, resultItem.address.postcode, resultItem.address.town, country_code]
.filter(Boolean)
.map((v) => v.trim())
.join(', ');
const result: geocode_output = {
position: [resultItem.lon, resultItem.lat].map(Number).map((value: number) => truncateToDecimals(value, 5)) as [number, number],
address: formattedAddress || null,
postcode: resultItem.address.postcode || null,
country: country_code,
};
return result;
};
import { describe, expect, it } from 'vitest';
import { geocodeWithAzure, geocodeWithOSM } from '#api/connector/helpers.ts';
describe.skip('Connector helpers', () => {
describe('geocodeWithOSM', () => {
it('should return a point', async () => {
const result = await geocodeWithOSM('400 Broad St, Seattle');
expect(result).toEqual({
address: '400 Broad Street, 98109, US',
country: 'US',
position: [expect.any(Number), expect.any(Number)],
postcode: '98109',
});
});
it('should return null', async () => {
const result = await geocodeWithOSM('#*-');
expect(result).toEqual(null);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment