OpenCageData / geosearch

OpenCage geosearch js client
MIT License
12 stars 6 forks source link

OpenCage - geosearch

[![header](/resources/OpenCage-geosearch-header.png)](https://opencagedata.com/geosearch)

A JavaScript library that lets you quickly add a search box and help your users find locations

[![Node.js CI](https://github.com/OpenCageData/geosearch/actions/workflows/node.js.yml/badge.svg)](https://github.com/OpenCageData/geosearch/actions/workflows/node.js.yml) [![Version](https://img.shields.io/npm/v/@opencage/geosearch-core.svg?style=flat-square)](https://www.npmjs.com/package/@opencage/geosearch-core) [![codecov](https://codecov.io/gh/OpenCageData/geosearch/branch/master/graph/badge.svg?token=VAZ0RZCGL3)](https://codecov.io/gh/OpenCageData/geosearch) [![MIT License](https://img.shields.io/badge/License-MIT-green.svg?style=flat-square)](LICENSE)

To get started you need:

This library comes as a plugin on Algolia's Autocomplete, which creates an input and provides the interactivity and accessibility attributes.

By configuring the two required parameters (container and key), and configuring the CORS header in your OpenCage dashboard you can have an interactive geosearch experience for places (countries, states/provinces, cities/towns/villages, suburbs/neighbourhoods, major POIS) around the world.

Note: to learn more about this service please see the OpenCage geosearch site (especially the FAQ section).

Example

header

See a configurable, live demo on the OpenCage site, or play with the html/css/js on codepen.

We also have tutorials/examples for integration on a map: Leaflet, OpenLayers, MapLibre.

Usage

For convenience, this repository is published as multiple packages. For a simple usage, we bundle it with the Algolia's Autocomplete. To get started, with a simple HTML page, you need a container to anchor the geosearch into:

<div id="place"></div>

Then, insert your search experience into it by calling the algoliaAutocomplete function, providing :

Make sure to provide a container (e.g., a div), not an input. The Geosearch generates a fully accessible search box.

Please note: a geosearch key is unrelated to the keys for the OpenCage geocoding API. Geosearch keys are of the form oc_gs_... and will need to be configured for a specific domain in your OpenCage account dashboard.

<script type="text/javascript">
  opencage.algoliaAutocomplete({
    container: '#place',
    plugins: [
      opencage.OpenCageGeoSearchPlugin(
        {
          key: 'YOUR-GEOSEARCH-KEY',
        },
        // optional event handlers:
        {
          onSelect: function handleSelect(params) {
            console.log('Selected Item is', params.item);
            const latlng = [params.item.geometry.lat, params.item.geometry.lng];
            // do something with the coords
            console.log('Selected result coords', latlng);
          },
          onSubmit: function handleSubmit(params) {
            // Do something with the selected and then submitted value
            console.log('Submit with', params.state.query);
          },
        }
      ),
    ],
  });
</script>

and to run it, just add the following resources to the header of the HTML page:

<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/@opencage/geosearch-bundle/dist/css/autocomplete-theme-classic.min.css"
/>
<script src="https://cdn.jsdelivr.net/npm/@opencage/geosearch-bundle"></script>

Optional configuration

opencage.OpenCageGeoSearchPlugin(options, events);

1. Options

In addition to the mandatory key parameter, the following optional parameters may also be set

The value of the bounds parameter should be specified as two coordinate points forming the south-west and north-east corners of a bounding box (min longitude, min latitude, max longitude, max latitude).

Example usage: bounds: '-0.563160,51.280430,0.278970,51.683979'

Values that are not valid coordinates are ignored. We have built a small, map-based tool to easily see bounds values.

The country code is a two letter code as defined by the ISO 3166-1 Alpha 2 standard. E.g. gb for the United Kingdom, fr for France, us for United States.

Example usage: countrycode: 'de'

Non-two letter country codes are ignored.

A two letter language code (such as es for Spanish or de for German), or native in which case we will attempt to return the response in the local language. Currently supported languages are: de, en, es, fr.

Example usage: language: 'de'

If no language is explicitly specified, we default to English en.

We hope to add more languages in the future. Please get in touch if lack of a certain language is preventing you from becoming a customer.

Default is 5. Maximum allowable value is 10.

Example usage: limit: 3

Default is 300.

Example usage: debounce: 250

Default is No results..

Example usage: noResults: 'Pas de résultat.'

2. Events

By default, this is an empty function.

Function parameter type:

(params:
  { state: AutocompleteState,
  ...setters,
  event: Event,
  item: TItem,
  itemInputValue: string,
  itemUrl: string,
  source: AutocompleteSource }
  ) => void

By default, this is an empty function.

Function parameter type:

(params:
  { state: AutocompleteState,
  ...setters,
  event: Event,
  item: TItem,
  itemInputValue: string,
  itemUrl: string,
  source: AutocompleteSource }
  ) => void`| defaults to`({ setIsOpen }) => setIsOpen(false)

By default, this is an empty function.

Function parameter type:

(params:
  { state: AutocompleteState,
  event: Event,
  ...setters }
  ) => void

Tweaking the look and feel

Check Algolia's Autocomplete CSS styles

Multiple datasources

It is possible to query not just geosearch but also other datasources. Please see our examples.

React

In the /examples directory you can find an example implemenation with React.

Geosearch on a map

We have tutorials showing how to integrate geosearch with a Leaflet map or OpenLayers, and a MapLibre codepen example.

Packages

@opencage/geosearch-bundle

For those who just want a simple HTML / JS integration

This package bumdles the Algolia Autocomplete and our GeoSearch plugin.

@opencage/geosearch-core

For those is using a javascript dependency manager

This is the core package: the GeoSearch plugin to use with Algolia Autocomplete.

@opencage/leaflet-opencage-geosearch

This is a plugin for the well-known map API leaflet. See our integration tutorial.

@opencage/ol-opencage-geosearch

This is a plugin for the well-known map API OpenLayers. See our integration tutorial.

Browser support / Polyfills

This project is written with the latest technologies in mind. Thereby it is required to include a polyfill when you wish to support older browsers:

Build and develop

Please refer to the following developer's notes

Issues

Find a bug or want to request a new feature? Please let us know by submitting an issue.

Please Note

Geosearch is an entirely different service than geocoding. OpenCage also operates a forward and reverse geocoding API, please don't confuse the geosearch service with the geocoding API.

Learn more about the difference between geosearch and geocoding.

License

Licensed under the MIT License

A copy of the license is available in the repository's LICENSE file.

Who is OpenCage GmbH?

OpenCage Logo

We run the OpenCage Geocoding API. Learn more about us.

We also run Geomob, a series of regular meetups for location based service creators, where we do our best to highlight geoinnovation. If you like geo stuff, you will probably enjoy the Geomob podcast.