diff --git a/README.md b/README.md index c0fee8b..08544a7 100755 --- a/README.md +++ b/README.md @@ -26,6 +26,7 @@ The plugin supports many different data providers: - [Plus codes](https://plus.codes/) (formerly OpenLocationCode) (requires [open-location-code](https://www.npmjs.com/package/open-location-code)) - [ArcGIS](https://developers.arcgis.com/features/geocoding/) - [Azure Maps Geocoding](https://www.microsoft.com/en-us/maps/azure/location-services/geocoding) +- [OpenGeocoding](https://opengeocoding.com/) The plugin can easily be extended to support other providers. Current extensions: diff --git a/spec/mockFetchRequest.ts b/spec/mockFetchRequest.ts index 6b27911..55f9e6a 100644 --- a/spec/mockFetchRequest.ts +++ b/spec/mockFetchRequest.ts @@ -3,9 +3,10 @@ import { expect, vi } from 'vite-plus/test'; export async function mockFetchRequest( url: string, response: unknown, - trigger: () => T + trigger: () => T, + extraHeaders?: Record ): Promise { - const headers = { Accept: 'application/json' }; + const headers = { Accept: 'application/json', ...extraHeaders }; global.fetch = vi.fn(() => Promise.resolve({ ok: true, diff --git a/spec/opengeocoding.spec.ts b/spec/opengeocoding.spec.ts new file mode 100644 index 0000000..c2760dc --- /dev/null +++ b/spec/opengeocoding.spec.ts @@ -0,0 +1,100 @@ +import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; +import { mockFetchRequest } from './mockFetchRequest'; +import { + OpenGeocoding, + OpenGeocodingAddress, + OpenGeocodingReverseResponse +} from '../src/geocoders/opengeocoding'; + +describe('L.Control.Geocoder.OpenGeocoding', () => { + afterEach(() => vi.clearAllMocks()); + const apiKey = { 'x-api-key': 'og_browser' }; + + it('requires an API key', () => { + expect(() => new OpenGeocoding()).toThrow('OpenGeocoding requires an API key.'); + }); + + it('geocodes Rådhuspladsen 1 with the key in a header', async () => { + const geocoder = new OpenGeocoding({ apiKey: 'og_browser' }); + const address = { + displayName: 'Rådhuspladsen 1, 1550 København V, Danmark', + goodMatch: true, + geoCoordinates: { lat: 55.6759, lon: 12.5694 } + } satisfies OpenGeocodingAddress; + const result = await mockFetchRequest( + 'https://api.opengeocoding.com/v1/search?addressString=R%C3%A5dhuspladsen+1%2C+K%C3%B8benhavn', + address, + () => geocoder.geocode('Rådhuspladsen 1, København'), + apiKey + ); + + expect(result).toHaveLength(1); + expect(result[0].name).toBe('Rådhuspladsen 1, 1550 København V, Danmark'); + expect(result[0].center).toStrictEqual({ lat: 55.6759, lng: 12.5694 }); + expect(result[0].bbox).toStrictEqual({ + _northEast: { lat: 55.6759, lng: 12.5694 }, + _southWest: { lat: 55.6759, lng: 12.5694 } + }); + expect(result[0].properties).toStrictEqual(address); + }); + + it('returns no results for an empty response', async () => { + const geocoder = new OpenGeocoding({ apiKey: 'og_browser' }); + const result = await mockFetchRequest( + 'https://api.opengeocoding.com/v1/search?addressString=xqzjvw', + {}, + () => geocoder.geocode('xqzjvw'), + apiKey + ); + expect(result).toStrictEqual([]); + }); + + it('reads omitted zero coordinates as 0 and uses the bounding box', async () => { + const geocoder = new OpenGeocoding({ apiKey: 'og_browser' }); + const result = await mockFetchRequest( + 'https://api.opengeocoding.com/v1/search?addressString=Gulf+of+Guinea', + { + displayName: 'Gulf of Guinea', + geoCoordinates: { + lon: 1.5, + boundingBox: { minLat: -2, minLon: -1, maxLat: 2, maxLon: 4 } + } + } satisfies OpenGeocodingAddress, + () => geocoder.geocode('Gulf of Guinea'), + apiKey + ); + expect(result[0].center).toStrictEqual({ lat: 0, lng: 1.5 }); + expect(result[0].bbox).toStrictEqual({ + _northEast: { lat: 2, lng: 4 }, + _southWest: { lat: -2, lng: -1 } + }); + }); + + it('reverse geocodes with the configured limit', async () => { + const geocoder = new OpenGeocoding({ apiKey: 'og_browser', reverseLimit: 2 }); + const response = { + results: [ + { + address: { + displayName: 'Rådhuspladsen 1, 1550 København V, Danmark', + geoCoordinates: { lat: 55.6759, lon: 12.5694 } + }, + distanceM: 4.2, + layer: 'address' + }, + { address: { displayName: 'No coordinates' }, layer: 'address' } + ] + } satisfies OpenGeocodingReverseResponse; + const result = await mockFetchRequest( + 'https://api.opengeocoding.com/v1/reverse?lat=55.676&lon=12.569&size=2', + response, + () => geocoder.reverse({ lat: 55.676, lng: 12.569 }, 1), + apiKey + ); + + expect(result).toHaveLength(1); + expect(result[0].name).toBe('Rådhuspladsen 1, 1550 København V, Danmark'); + expect(result[0].center).toStrictEqual({ lat: 55.6759, lng: 12.5694 }); + expect(result[0].properties).toStrictEqual(response.results[0]); + }); +}); diff --git a/src/geocoders/index.ts b/src/geocoders/index.ts index d9bc545..3683246 100644 --- a/src/geocoders/index.ts +++ b/src/geocoders/index.ts @@ -11,6 +11,7 @@ export * from './neutrino'; export * from './nominatim'; export * from './open-location-code'; export * from './opencage'; +export * from './opengeocoding'; export * from './pelias'; export * from './photon'; export * from './what3words'; diff --git a/src/geocoders/opengeocoding.ts b/src/geocoders/opengeocoding.ts new file mode 100644 index 0000000..c40b3f1 --- /dev/null +++ b/src/geocoders/opengeocoding.ts @@ -0,0 +1,114 @@ +import * as L from 'leaflet'; +import { getJSON } from '../util'; +import { GeocoderOptions, geocodingParams, GeocodingResult, IGeocoder, reverseParams } from './api'; + +export interface OpenGeocodingOptions extends GeocoderOptions { + /** + * Maximum number of reverse geocoding results + */ + reverseLimit: number; +} + +/** + * Implementation of the [OpenGeocoding](https://opengeocoding.com/) API. + * + * Use a browser key restricted to your site's origins; the API rejects keys + * in the URL, so the key is sent in the `x-api-key` header. + * + * Search returns at most one result. Suggestions are not wired up: the + * autocomplete endpoint returns place IDs without coordinates. + */ +export class OpenGeocoding implements IGeocoder { + options: OpenGeocodingOptions = { + serviceUrl: 'https://api.opengeocoding.com/v1', + reverseLimit: 1 + }; + + constructor(options?: Partial) { + L.Util.setOptions(this, options); + if (!this.options.apiKey) { + throw new Error('OpenGeocoding requires an API key.'); + } + } + + async geocode(query: string): Promise { + const params = geocodingParams(this.options, { addressString: query }); + const data = await getJSON( + this.options.serviceUrl + '/search', + params, + this._headers() + ); + const result = this._parseAddress(data); + return result ? [result] : []; + } + + async reverse(location: L.LatLngLiteral, _scale: number): Promise { + const params = reverseParams(this.options, { + lat: location.lat, + lon: location.lng, + size: this.options.reverseLimit + }); + const data = await getJSON( + this.options.serviceUrl + '/reverse', + params, + this._headers() + ); + return (data.results || []) + .map(r => this._parseAddress(r.address, r)) + .filter((r): r is GeocodingResult => !!r); + } + + private _headers() { + return { 'x-api-key': this.options.apiKey! }; + } + + private _parseAddress( + address: OpenGeocodingAddress | undefined, + properties: unknown = address + ): GeocodingResult | undefined { + const c = address?.geoCoordinates; + if (!c) { + return undefined; + } + // Protobuf JSON omits zero values, so a missing lat or lon means 0. + const center = new L.LatLng(c.lat ?? 0, c.lon ?? 0); + const b = c.boundingBox; + return { + name: address!.displayName ?? '', + center, + bbox: b + ? new L.LatLngBounds([b.minLat ?? 0, b.minLon ?? 0], [b.maxLat ?? 0, b.maxLon ?? 0]) + : new L.LatLngBounds(center, center), + properties + }; + } +} + +/** + * [Class factory method](https://leafletjs.com/reference.html#class-class-factories) for {@link OpenGeocoding} + * @param options the options + */ +export function opengeocoding(options?: Partial) { + return new OpenGeocoding(options); +} + +/** + * @internal + */ +export interface OpenGeocodingAddress { + displayName?: string; + goodMatch?: boolean; + geoCoordinates?: { + lat?: number; + lon?: number; + boundingBox?: { minLat?: number; minLon?: number; maxLat?: number; maxLon?: number }; + }; + addressDetails?: Record; +} + +/** + * @internal + */ +export interface OpenGeocodingReverseResponse { + results?: { address?: OpenGeocodingAddress; distanceM?: number; layer?: string }[]; +} diff --git a/src/util.ts b/src/util.ts index f4e9379..f0cdda6 100644 --- a/src/util.ts +++ b/src/util.ts @@ -51,8 +51,12 @@ export function htmlEscape(string?: string): string { /** * @internal */ -export function getJSON(url: string, params: Record): Promise { - const headers = { Accept: 'application/json' }; +export function getJSON( + url: string, + params: Record, + extraHeaders?: Record +): Promise { + const headers = { Accept: 'application/json', ...extraHeaders }; const request = new URL(url); Object.entries(params).forEach(([key, value]) => { (Array.isArray(value) ? value : [value]).forEach(v => {