Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
5 changes: 3 additions & 2 deletions spec/mockFetchRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ import { expect, vi } from 'vite-plus/test';
export async function mockFetchRequest<T>(
url: string,
response: unknown,
trigger: () => T
trigger: () => T,
extraHeaders?: Record<string, string>
): Promise<T> {
const headers = { Accept: 'application/json' };
const headers = { Accept: 'application/json', ...extraHeaders };
global.fetch = vi.fn(() =>
Promise.resolve({
ok: true,
Expand Down
100 changes: 100 additions & 0 deletions spec/opengeocoding.spec.ts
Original file line number Diff line number Diff line change
@@ -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]);
});
});
1 change: 1 addition & 0 deletions src/geocoders/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
114 changes: 114 additions & 0 deletions src/geocoders/opengeocoding.ts
Original file line number Diff line number Diff line change
@@ -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<OpenGeocodingOptions>) {
L.Util.setOptions(this, options);
if (!this.options.apiKey) {
throw new Error('OpenGeocoding requires an API key.');
}
}

async geocode(query: string): Promise<GeocodingResult[]> {
const params = geocodingParams(this.options, { addressString: query });
const data = await getJSON<OpenGeocodingAddress>(
this.options.serviceUrl + '/search',
params,
this._headers()
);
const result = this._parseAddress(data);
return result ? [result] : [];
}

async reverse(location: L.LatLngLiteral, _scale: number): Promise<GeocodingResult[]> {
const params = reverseParams(this.options, {
lat: location.lat,
lon: location.lng,
size: this.options.reverseLimit
});
const data = await getJSON<OpenGeocodingReverseResponse>(
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<OpenGeocodingOptions>) {
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<string, unknown>;
}

/**
* @internal
*/
export interface OpenGeocodingReverseResponse {
results?: { address?: OpenGeocodingAddress; distanceM?: number; layer?: string }[];
}
8 changes: 6 additions & 2 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,12 @@ export function htmlEscape(string?: string): string {
/**
* @internal
*/
export function getJSON<T>(url: string, params: Record<string, unknown>): Promise<T> {
const headers = { Accept: 'application/json' };
export function getJSON<T>(
url: string,
params: Record<string, unknown>,
extraHeaders?: Record<string, string>
): Promise<T> {
const headers = { Accept: 'application/json', ...extraHeaders };
const request = new URL(url);
Object.entries(params).forEach(([key, value]) => {
(Array.isArray(value) ? value : [value]).forEach(v => {
Expand Down