Leaflet GeoSearch
Edit page
IntroductionUsageLeaflet Control
Providers
AlgoliaBingEsriGeocode EarthGoogleHereLocationIQOpenCageOpenStreetMapPeliasCustom ProvidersCustom Server ResponseSharingGeoapifyGeoApiFrLegacyGoogle

Custom Providers

It's possible to create your own providers either by creating one from scratch, or extending an existing one.

The most trivial one to extend, is the OpenStreetMap provider. As Nominatim is open source, and can be self hosted, the provider allows for easy extension.

import { OpenStreetMapProvider } from 'leaflet-geosearch';
class MyProvider extends OpenStreetMapProvider {
constructor(options) {
super({
...options,
searchUrl: 'https://example.com/api/search',
reverseUrl: 'https://example.com/api/reverse',
});
}
}

When the constructor is the only thing you need to override, it might be sufficient to provide the options during initialization:

const provider = new OpenStreetMapProvider({
searchUrl: 'https://example.com/api/search',
reverseUrl: 'https://example.com/api/reverse',
});

However, custom providers can be easier to share, and have a single source of truth. As you don't need to manage the URL's on various places throughout your codebase.

Custom Server Response

When you need to adjust the provider to support a different json data shape, you might want to override more than just the urls.

Theparse method allows you to transform the server response, to the SearchResult types.

The endpoint method is there to select the correct endpoint, based on the search parameters.

import { JsonProvider } from 'leaflet-geosearch';
class MyProvider extends JsonProvider {
endpoint({ query, type }) {
// Result: https://example.com/api/search?q=some%20address&f=json
return this.getUrl('https://example.com/api/search', {
q: query,
f: 'json',
});
}
parse({ data }) {
// Note that `data` is the raw result returned by the server. This
// method should return data in the SearchResult format.
return data.map((x) => ({
x: data.x,
y: data.y,
label: data.label,
bounds: data.bounds,
}));
}
}

Sharing

When you've build a custom provider that can be used by others, please consider opening a pull-request, or publishing it to npm.