New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@placekit/autocomplete-js

Package Overview
Dependencies
Maintainers
2
Versions
43
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@placekit/autocomplete-js

PlaceKit Autocomplete JavaScript library

  • 1.0.0-alpha.6
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
434
decreased by-6.47%
Maintainers
2
Weekly downloads
 
Created
Source

PlaceKit Autocomplete JS Library

All-in-one autocomplete experience for your web apps

NPM LICENSE

Quick startFeaturesReferenceCustomizeDocumentationLicense


PlaceKit Autocomplete JavaScript Library is a standalone address autocomplete field for your application, built on top of our PlaceKit JS client. Under the hood it relies on Popper to position the suggestions list, and on Flagpedia to display flags on country results.

If you already use a components library with an autocomplete field, or need a more advanced usage, please refer to our PlaceKit JS client reference and its examples.

For React implementations, check our PlaceKit Autocomplete React library.

✨ Features

  • Standalone and lightweight: about 12kb of JS, and 4kb of CSS, gzipped
  • Cross browser: compatible across all major modern browsers
  • Non-invasive: use and style your own input element
  • Customizable and extensible with events and hooks
  • TypeScript compatible

🎯 Quick start

CDN

First, import the library and the default stylesheet into the <head> tag in your HTML:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@placekit/autocomplete-js@1.0.0-alpha.4/dist/placekit-autocomplete.min.css" />
<script src="https://cdn.jsdelivr.net/npm/@placekit/autocomplete-js"></script>

After importing the library, placekitAutocomplete becomes available as a global:

<input type="search" placeholder="Search place..." class="pka-input" id="placekit" />
<script>
  const pka = placekitAutocomplete('<your-api-key>', {
    inputSelector: '#placekit',
    // other options...
  });
</script>

Or if you are using native ES Modules:

<script type="module">
  import placekit from 'https://cdn.jsdelivr.net/npm/@placekit/autocomplete-js@1.0.0-alpha.4/dist/placekit-autocomplete.esm.js';
  const pka = placekitAutocomplete(/* ... */);
  // ...
</script>

NOTE: Make sure to call placekitAutocomplete after the DOM is loaded so the input can be found.

NPM

First, install PlaceKit Autocomplete using npm package manager:

npm install --save @placekit/autocomplete-js

Then import the package and perform your first address search:

// CommonJS syntax:
const placekitAutocomplete = require('@placekit/autocomplete-js');

// ES6 Modules syntax:
import placekit from '@placekit/autocomplete-js';

const pka = placekit('<your-api-key>', {
  target: '#placekit',
  // other options...
});

Don't forget to import @placekit/autocomplete-js/dist/placekit-autocomplete.css if you want to use our default style. If you have trouble importing CSS from node_modules, copy/paste its content into your own CSS.

👉 Check out our examples for different use cases!

🧰 Reference

placekitAutocomplete()

PlaceKit Autocomplete initialization function returns a PlaceKit Autocomplete client, named pka in all examples.

const pka = placekitAutocomplete('<your-api-key>', {
  language: 'en',
  maxResults: 10,
});
ParameterTypeDescription
apiKeystringAPI key
optionskey-value mapping (optional)Global parameters (see options)

pka.input

Input field element passed as target option, read-only.

console.log(pka.input); // <input ... />

pka.options

Options from both PlaceKit Autocomplete and PlaceKit JS client, read-only.

console.log(pka.options); // { "target": <input ... />, "language": "en", "maxResults": 10, ... }
OptionFromTypeDefaultDescription
targetAutoCompletestring|Element-Target input element or (unique) selector.
offsetAutoCompleteinteger4Gap between input and suggestions list in pixels.
templateAutoComplete(item: object) => stringsee index.jsSuggestion item formatting function.
formatValueAutoComplete(item: object) => stringsee index.jsInput value formatting function when selected from list.
strategyAutoComplete`'absolute''fixed'`absolute
flipAutoCompletebooleanfalseFlip position top when overflowing.
classNameAutoCompletestringundefinedAdditional suggestions panel CSS class(es).
maxResultsJS clientinteger5Number of results per page.
languageJS clientstring?undefinedLanguage of the results, two-letter ISO language code.
typesJS clientstring[]?undefinedType of results to show. Array of accepted values: street, city, country, airport, bus, train, townhall, tourism. Prepend - to omit a type like ['-bus']. Unset to return all.
countriesJS clientstring[]?undefinedLimit results to given countries. Array of two-letter ISO country codes.
coordinatesJS clientstring?undefinedCoordinates to search around. Automatically set when calling pka.requestGeolocation().

pka.configure()

Updates search parameters (only JS client options!). Returns the instance so you can chain methods.

pka.configure({
  language: 'fr',
  maxResults: 5,
});
ParameterTypeDescription
optskey-value mapping (optional)Global parameters (see options)

pka.on()

Register event handlers, methods can be chained.

pka.on('open', () => {})
  .on('close', () => {})
  .on('results', (query, results) => {})
  .on('pick', (value, item, index) => {})
  .on('error', (error) => {})
  .on('freeForm', (isFreeForm) => {})
  .on('geolocation', (hasGeolocation, position) => {});

If you register a same event twice, the first one will be replaced. So, to remove an handler, simply assign undefined:

pka.on('open'); // clears handler for 'open' event
Events
open

Triggered when panel opens.

close

Triggered when panel closes.

results

Triggered when suggestions list gets updated, same as when the user types or enables geolocation.

ParameterTypeDescription
querystringInput value.
resultsobject[]Results returned from API.
pick

Triggered when user selects an item from the suggestion list by clicking on it or pressing ENTER after using the keyboard navigation.

ParameterTypeDescription
valuestringInput value (value returned by options.formatValue()).
itemobjectAll item details returned from API.
indexnumberPosition of the selected item in the suggestions list, zero-based.
error

Triggered on server error.

ParameterTypeDescription
errorobjectError details.
freeForm

Triggered when isFreeForm value changes.

ParameterTypeDescription
isFreeFormbooleantrue on user input, false on pick event.

Mostly intended to update a local React state, because pka.isFreeForm isn't stateful.

geolocation

Triggered when hasGeolocation value changes (a.k.a. when pka.requestGeolocation is called).

ParameterTypeDescription
hasGeolocationbooleantrue if granted, false if denied.
positionGeolocationPositionPassed when hasGeolocation is true.

Mostly intended to update a local React state, because pka.hasGeolocation isn't stateful.

pka.handlers

Reads registered event handlers, read-only.

pka.on('open', () => {});
console.log(pka.handlers); // { open: ... }

pka.isFreeForm

Read-only boolean, true if the input has a free form value or false if value is selected from the suggestions. The latter can only occur when the user has clicked on a suggestion or pressed ENTER after navigating the suggestions with the keyboard.

console.log(pka.isFreeForm); // true or false

This value comes handy if you need to implement a strict validation of the address, but we don't interfere with how to implement it as input validation is always very specific to the project's stack.

pka.requestGeolocation()

Requests device's geolocation (browser-only). Returns a Promise with a GeolocationPosition object.

pka.requestGeolocation({ timeout: 10000 }).then((pos) => console.log(pos.coords));
ParameterTypeDescription
optskey-value mapping (optional)navigator.geolocation.getCurrentPosition options
cancelUpdateboolean (optional)If false (default), suggestions list updates immediately based on device location.

The location will be store in the coordinates global options, you can still manually override it.

pka.hasGeolocation

Reads if device geolocation is activated or not (read-only).

console.log(pka.hasGeolocation); // true or false

pka.open()

Opens the suggestion panel.

pka.open();

pka.close()

Closes the suggestion panel.

pka.close();

pka.clear()

Clears the input value, focus the field, and closes the suggestion panel.

pka.clear();

pka.destroy()

Removes the suggestions panel from the DOM and clears all event handlers from window and input that were added by PlaceKit Autocomplete.

pka.destroy();

💅 Customize

You have full control over the input element as PlaceKit Autocomplete doesn't style nor alter it by default. We still provide a style that you can apply by adding the .pka-input class to your input element.

Colors, border-radius, font and overall scale (in rem) are accessible over variables:

:root {
  --pka-scale: 1rem;
  --pka-color-accent: 1, 73, 200;
  --pka-color-black: 29, 41, 57;
  --pka-color-darker: 52, 64, 84;
  --pka-color-dark: 152, 162, 179;
  --pka-color-light: 207, 213, 221;
  --pka-color-lighter: 243, 244, 246;
  --pka-color-white: 255, 255, 255;
  --pka-border-radius: 6px;
  --pka-font-family: system-ui, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
}

/* dark mode overrides */
body.dark,
body[data-theme="dark"] {
  --pka-color-accent: 55, 131, 249;
}

For advanced customization, refer to our stylesheet to learn about the available classes if you need to either override some or start a theme from scratch.

A dark mode is available whenever you add .dark class or data-theme="dark" attribute to the <body> element.

⚠️ NOTE: you are not allowed to hide the PlaceKit logo unless we've delivered a special authorization. To request one, please contact us using our contact form.

⚖️ License

PlaceKit Autocomplete JS Library is an open-sourced software licensed under the MIT license.

FAQs

Package last updated on 20 Dec 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc