2.2.3 • Published 5 months ago

places-autocomplete-svelte v2.2.3

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

Places (New) Autocomplete Svelte

This Svelte component provides a user-friendly way to search for and retrieve detailed address information within your SvelteKit applications, leveraging the power of the Google Maps Places (New) Autocomplete API. It comes with default styling using Tailwind CSS, which you can fully customise.

Features

  • Seamless SvelteKit Integration: Easily add the component to your SvelteKit projects.
  • Real-time Autocomplete Suggestions: As the user types, address suggestions appear dynamically.
  • Comprehensive Address Details: Retrieve detailed information, including street address, city, state/province, postal code, country, and more.
  • Country/Region Filtering: Narrow down search results by specifying target countries or regions.
  • Customizable Styles: Tailor the component's appearance to match your application's design by overriding the default Tailwind CSS classes.
  • Flexible Data Control: Choose the specific data fields you want to retrieve using the fetchFields property.
  • Keyboard Navigation & Accessibility: Use keyboard navigation for selecting suggestions, ensuring accessibility for all users.

Demo

See a live demo of the component in action: Basic Example

Reactive parameters - change the search criteria based on user input, like filtering by country or change results language.

Customise request parameters - construct a requestParams object and control various aspects of the search, including language, region, and more.

Requirements

  • Google Maps API Key with the Places API (New) enabled. Refer to Use API Keys for detailed instructions.

Installation Svelte 5

npm i places-autocomplete-svelte

Installation Svelte 4

npm i places-autocomplete-svelte@1.0.1

Basic Usage

  1. Replace '___YOUR_API_KEY___' with your actual Google Maps API Key.
  2. Use the onResponse callback to handle the response.
<script>
import { PlaceAutocomplete } from 'places-autocomplete-svelte';

//Recommended: Store your key securely as an environment variable
const PUBLIC_GOOGLE_MAPS_API_KEY = '___YOUR_API_KEY___';


let fullResponse = $state('')
let onResponse = (response) => {
	fullResponse = response;
};
</script>

<PlaceAutocomplete  {onResponse} {PUBLIC_GOOGLE_MAPS_API_KEY} />

<p>Response Object: {JSON.stringify(fullResponse, null, 2)}</p>

Component Properties

PropertyTypeDescriptionRequiredDefault Value
PUBLIC_GOOGLE_MAPS_API_KEYStringYour Google Maps Places API Key.Yes
onResponseCustomEventDispatched when a place is selected, containing the place details in event.detail.Yes
onErrorCustomEventDispatched when an error occurs, with the error message in event.detail.No
requestParamsObjectObject for additional request parameters (e.g., types, bounds, origin, region, language). See AutocompleteRequest.No{}
fetchFieldsArrayArray of place data fields to return. See Supported Fields documentation for a comprehensive list of available fields. Note that the Places Autocomplete service does not support the following fields, even if they are available in the Place Details API: geometry, icon, name, permanentlyClosed, photo, placeId, url, utcOffset, vicinity, openingHours, icon, and name. If you need these fields, you must make a separate call to the Place Details API using the returned place_id.No['formattedAddress', 'addressComponents']
optionsObjectOptions for customizing the component's behavior and appearance. See "Customization" below.NoSee default values in "Customization"

Customization

Options

PropertyTypeDescriptionDefault Value
autofocusbooleanIf true, the input field will be focused automatically when the component mounts.false
placeholderStringPlaceholder text for the input field."Search..."
autocompletestringHTML autocomplete attribute for the input field. Set to "off" to disable browser autocomplete."off"
distancebooleanIf true, and if an origin is specified in requestParams, displays the distance to each suggestion. The distance is calculated as a geodesic in meters.false
distance_unitskm or milesSpecified the distance units.km
classesObjectObject to override default Tailwind CSS classes.See styling

Styling

Customise the component's appearance by providing an object to the classes property. This object should contain key-value pairs, where the keys correspond to the component's elements and the values are your custom CSS class names. See styling for details.

Request Parameters (requestParams)

Fine-tune the autocomplete search with the requestParams property. This property accepts an object corresponding to the AutocompleteRequest object in the Google Maps API documentation. See this request parameters for more details. Here are some common examples:

<script>
// ... other imports

/**
 * @type object optional
 * AutocompleteRequest properties
 */
const requestParams = {
	/**
	 * @type string optional
	 */
	language : 'en-GB',
	/**
	 * @type string optional
	 */
	region : 'GB',
}

/**
 * @type object optional
 * Options
 */
const options = {
	autofocus: false,
	autocompete: 'off',
	placeholder: 'Start typing your address',
	distance: true,
	distance_units: 'km' // or miles
};

/**
 * @type array optional
 */
const fetchFields = ['formattedAddress', 'addressComponents'];
</script>

<PlaceAutocomplete 
	{onError} 
	{onResponse} 
	{PUBLIC_GOOGLE_MAPS_API_KEY} 
	{requestParams}
	{options} 
	{fetchFields}
	
/>

Error Handling

Use the onError event handler to gracefully manage any errors that may occur during the autocomplete process:

<script>
// ... other imports

// Error handler
let pacError = '';
let onError = (error: string) => {
	console.error(error);
	pacError = error;
};
</script>

<PlaceAutocomplete 
{onResponse} 
{onError} 
{PUBLIC_GOOGLE_MAPS_API_KEY} />

{#if pacError}
	<p class="error">{pacError}</p>
{/if}

Contributing

Contributions are welcome! Please open an issue or submit a pull request on the GitHub.

License

MIT

2.1.9

5 months ago

2.2.1

5 months ago

2.1.2

8 months ago

2.2.0

5 months ago

2.1.1

8 months ago

2.2.3

5 months ago

2.1.4

6 months ago

2.2.2

5 months ago

2.1.3

7 months ago

2.1.6

6 months ago

2.1.5

6 months ago

2.1.8

5 months ago

2.0.9

8 months ago

2.1.7

6 months ago

2.0.8

8 months ago

2.1.0

8 months ago

2.0.7

9 months ago

2.0.6

9 months ago

2.0.0

9 months ago

1.0.1

12 months ago

1.0.0

12 months ago

0.0.1

12 months ago