Simple JS snippet to add a geocode.city-backed text input to an existing page.
I'm bad at Javascript (and worse at Purescript) so this is an old-school
style of snippet: include it on your page, make sure you have an element
with id geocode-city-autocomplete, and we're done. If you have an api key,
have that element provide it via a data-api-key attribute.
For example:
<body>
<div id="geocode-city-autocomplete" data-api-key="my-api-key" data-suggestion-count="10">
</div>
<script src="https://cdn.jsdelivr.net/gh/geocode-city/autocomplete@0.1.0.1/dist/geocode_city.min.js"></script>
</body>The element would ideally be empty: the script replaces it with its own input. All markup generated by the script has appropriately prefixed CSS classes, so you can style it to match your own app.
data-api-key: your api key.data-suggestion-count: how many suggestions to display. Defaults to 5, max is 100 (enforced by the server.)data-input-nameanddata-input-class: control thenameandinputattributes of the textual input.
You can listen to any of these events and find their data in the event.detail property.
citySelected: receives thecityobject that was selected by the user.citiesFound: receives an array ofcityobjects when a response has been received. Will not be raised if no results are found, or if there's errors.noCitiesFound: raised when the request succeeded, but no cities matched the query.lookupError: raised when the response fails, due to a client or server errors. The error message as parsed by the request handler is included inevent.detail.message.
Example of a city object:
{
"timezone": "Europe/Paris",
"region": "Île-de-France",
"population": 2138551,
"name": "Paris",
"longitude": 2.3488,
"latitude": 48.85341,
"district": "Paris",
"countryCode": "FR",
"country": "France"
}The component is unstyled, but CSS classes are used for each element; cf. the render function
in each of Autocomplete.Component and Autocomplete.Dropdown for the most up to date classes.
I distribute this project through jsdelivr. See NOTES for development commands, but for production, I just run:
npm run bundleAnd the dist/geocode_city.js file should be updated. Minification is offloaded
to jsdelivr for the time being.