places-autocomplete-js 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENCE +21 -0
  2. package/LICENSE +21 -0
  3. package/README.md +233 -0
  4. package/package.json +61 -0
package/LICENCE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Alexander Pechkarev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Alexander Pechkarev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,233 @@
1
+ # Places (New) Autocomplete - JavaScript Library
2
+
3
+ [![npm version](https://badge.fury.io/js/places-autocomplete-js.svg)](https://badge.fury.io/js/places-autocomplete-js)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+
6
+ A flexible and customizable vanilla JavaScript library leveraging the [Google Maps Places (New) Autocomplete API](https://developers.google.com/maps/documentation/javascript/place-autocomplete-overview). This library provides a user-friendly way to search for and retrieve detailed address information in any web application.
7
+
8
+ It handles API loading, session tokens for cost-effective usage, fetching suggestions with debouncing, keyboard navigation, highlighting matched text, and requesting place details, allowing you to focus on integrating the results into your application.
9
+
10
+
11
+
12
+ ## Places (New) Autocomplete – JavaScript Integration
13
+
14
+ Simply include a single script tag and handle the response in your JavaScript code.
15
+ [View Details](https://pacservice.pages.dev/)
16
+
17
+
18
+ ## Features
19
+
20
+ * Integrates with the modern **Google Places (New) Autocomplete API**.
21
+ * Automatically handles **session tokens** for cost management per Google's guidelines.
22
+ * **Debounced Input:** Limits API calls while the user is typing (configurable).
23
+ * **Suggestion Highlighting:** Automatically highlights the portion of text matching the user's input.
24
+ * **Customizable Styling:** Easily override default styles or apply your own using CSS classes passed in options. Built with sensible defaults (Tailwind CSS utility classes by default but can be entirely replaced).
25
+ * **Event Handling:** Provides `onResponse` and `onError` callbacks.
26
+ * **Configurable:** Control API parameters (`requestParams`) and component behavior/appearance (`options`).
27
+ * **Dynamic API Loading:** Loads the Google Maps API script on demand.
28
+
29
+
30
+
31
+ ## Demo
32
+
33
+ See a live demo of the library in action: [Basic Example](https://pacservice.pages.dev/)
34
+
35
+
36
+ ## Requirements
37
+
38
+ * **Google Maps API Key** with the Places API (New) enabled. Refer to [Use API Keys](https://developers.google.com/maps/documentation/javascript/get-api-key) for detailed instructions.
39
+
40
+ ## Installation
41
+
42
+ ```bash
43
+ npm install places-autocomplete-js
44
+ # or
45
+ yarn add places-autocomplete-js
46
+ ```
47
+
48
+
49
+
50
+ ## Basic Usage
51
+
52
+ 1. Replace `'___YOUR_API_KEY___'` with your actual **Google Maps API Key**.
53
+ 2. Use the `onResponse` callback to **handle the response**.
54
+
55
+ ```javascript
56
+ <script>
57
+ import { PlacesAutocompleteJs } from 'places-autocomplete-js;
58
+
59
+ document.addEventListener('DOMContentLoaded', () => {
60
+ try {
61
+ const autocomplete = new PlacesAutocompleteJs({
62
+ containerId: 'autocomplete-container',
63
+ googleMapsApiKey: 'YOUR_GOOGLE_MAPS_API_KEY', // Replace with your actual key
64
+ onResponse: (placeDetails) => {
65
+ console.log('Place Selected:', placeDetails);
66
+ // Example: document.getElementById('address-field').value = placeDetails.formattedAddress;
67
+ // Example: document.getElementById('place-name').textContent = placeDetails.displayName;
68
+ },
69
+ onError: (error) => {
70
+ console.error('Autocomplete Error:', error.message || error);
71
+ }
72
+ });
73
+
74
+ // Optional: You can interact with the instance later
75
+ // autocomplete.clear();
76
+ // autocomplete.destroy(); // To clean up
77
+
78
+ } catch (error) {
79
+ console.error("Failed to initialize PlacesAutocompleteJs:", error.message);
80
+ }
81
+ });
82
+
83
+ </script>
84
+
85
+ {#if placesError}
86
+ <div class="error-message" role="alert">
87
+ Error: {placesError}
88
+ </div>
89
+ {/if}
90
+ ...
91
+ <div id="autocomplete-container"></div>
92
+ ...
93
+ ```
94
+ ### Configuration
95
+
96
+ The `PlacesAutocompleteJs` class is initialized with a configuration object.
97
+
98
+ | Parameter | Type | Required | Description |
99
+ |--------------------------|----------|----------|------------------------------------------------------------------------------------------------------------|
100
+ | `containerId` | `string` | Yes | The ID of the HTML element where the autocomplete widget will be rendered. |
101
+ | `googleMapsApiKey` | `string` | Yes | Your Google Maps API Key with the Places API (New) enabled. |
102
+ | `googleMapsApiVersion` | `string` | No | The version of the Google Maps API to load (e.g., "weekly", "quarterly", "beta"). Defaults to "weekly". |
103
+ | `onResponse` | `function` | No | Callback function triggered with selected place details. Receives a `Place` object (see Google's docs). Default logs to console. |
104
+ | `onError` | `function` | No | Callback function triggered when an error occurs. Receives an `Error` object or string. Default logs to console. |
105
+ | `options` | `object` | No | Object to customize UI behavior and appearance. See "UI & Behavior Options" below. |
106
+ | `requestParams` | `object` | No | Object to customize the parameters sent to the Google Places Autocomplete API. See "API Request Parameters" below. |
107
+
108
+ ### UI & Behavior Options (`options`)
109
+
110
+ Passed within the main configuration object under the `options` key.
111
+
112
+ | Option | Type | Default | Description |
113
+ |----------------|---------------------------|-------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------|
114
+ | `placeholder` | `string` | `"Start typing your address ..."` | Placeholder text for the input field. |
115
+ | `debounce` | `number` | `100` | Delay in milliseconds before triggering an API request after user stops typing. Set to `0` to disable. |
116
+ | `distance` | `boolean` | `true` | Whether to attempt to show distance in suggestions (requires `origin` in `requestParams`). |
117
+ | `distance_units`| `'km' \| 'miles'` | `'km'` | Units to display distance in if `distance` is true. |
118
+ | `label` | `string` | `""` | Optional label text displayed above the input field. |
119
+ | `autofocus` | `boolean` | `false` | If `true`, automatically focuses the input field on initialization. |
120
+ | `autocomplete` | `string` | `'off'` | Standard HTML `autocomplete` attribute for the input field. |
121
+ | `classes` | `object` | *(See default classes below)* | Object to override default CSS classes for styling. See "Styling" section. |
122
+
123
+ ### API Request Parameters (`requestParams`)
124
+
125
+ Passed within the main configuration object under the `requestParams` key. These parameters are sent to the Google Places Autocomplete API. Refer to the [AutocompleteRequest documentation](https://developers.google.com/maps/documentation/javascript/reference/places-autocomplete-service#AutocompleteRequest) for all available options.
126
+
127
+ **Common `requestParams`:**
128
+
129
+ * `input`: (string) Automatically handled by the library based on user typing.
130
+ * `language`: (string) The language code, indicating in which language the results should be returned, if possible.
131
+ * `region`: (string) The region code, specified as a ccTLD ("top-level domain") two-character value.
132
+ * `includedRegionCodes`: (string[]) An array of up to 5 CLDR region codes to limit results to.
133
+ * `locationBias`: (google.maps.places.LocationBias)
134
+ * `locationRestriction`: (google.maps.places.LocationRestriction)
135
+ * `origin`: (google.maps.LatLngLiteral) The origin point from which to calculate straight-line distances to predictions (if `options.distance` is true).
136
+ * `sessionToken`: Automatically managed by this library.
137
+
138
+ **Example `requestParams`:**
139
+
140
+ ```javascript
141
+ const autocomplete = new PlacesAutocompleteJs({
142
+ // ... other config
143
+ requestParams: {
144
+ language: 'fr',
145
+ region: 'ca',
146
+ includedRegionCodes: ['ca'],
147
+ origin: { lat: 45.5019, lng: -73.5674 } // Montreal
148
+ }
149
+ });
150
+ ```
151
+
152
+ ### Styling (`options.classes`)
153
+
154
+ You can customize the appearance of the component by providing your own CSS classes via the `options.classes` object. The library uses a default set of classes (many are Tailwind CSS utility classes but can be entirely replaced).
155
+
156
+ Provide an object where keys are the component parts and values are the class strings you want to apply.
157
+
158
+ **Default Class Keys & Structure:**
159
+
160
+ * `section`: The main container section.
161
+ * `container`: The div containing the input and suggestions list.
162
+ * `label`: The label element (if `options.label` is provided).
163
+ * `input`: The main text input element.
164
+ * `icon_container`: Container for the optional icon.
165
+ * `icon`: SVG string for the icon.
166
+ * `ul`: The `<ul>` element for the suggestions list.
167
+ * `li`: Each `<li>` suggestion item.
168
+ * `li_current`: Class added to the currently highlighted/selected `<li>` (keyboard/mouse).
169
+ * `li_a`: The inner `<a>` or `<button>` element within each `<li>`.
170
+ * `li_a_current`: Class added to the inner element when its `<li>` is current.
171
+ * `li_div_container`: Container div within the `<a>`/`<button>`.
172
+ * `li_div_one`: First inner div (usually contains the main text).
173
+ * `li_div_one_p`: The `<p>` tag containing the main suggestion text (`@html` is used).
174
+ * `li_div_two`: Second inner div (usually contains the distance).
175
+ * `li_div_two_p`: The `<p>` tag containing the distance text.
176
+ * `kbd_container`: Container for the keyboard hint keys (Esc, Up, Down).
177
+ * `kbd_escape`: The `<kbd>` tag for the 'Esc' hint.
178
+ * `kbd_up`: The `<kbd>` tag for the 'Up Arrow' hint.
179
+ * `kbd_down`: The `<kbd>` tag for the 'Down Arrow' hint.
180
+ * `highlight`: **(New)** The class applied to the `<span>` wrapping the matched text within suggestions. Defaults to `'font-bold'`.
181
+
182
+ **Example: Overriding Classes**
183
+
184
+ ```javascript
185
+ const autocomplete = new PlacesAutocompleteJs({
186
+ // ... other config
187
+ options: {
188
+ classes: {
189
+ input: 'my-custom-input form-control', // Replace default input style
190
+ ul: 'my-custom-dropdown-styles', // Custom dropdown style
191
+ li_current: 'my-active-suggestion', // Custom highlight for selected item
192
+ highlight: 'my-search-highlight' // Custom style for matched text
193
+ }
194
+ }
195
+ });
196
+ ```
197
+
198
+ Then, style these classes in your CSS:
199
+
200
+ ```css
201
+ .my-custom-input {
202
+ padding: 10px;
203
+ border: 1px solid #ccc;
204
+ border-radius: 4px;
205
+ }
206
+ .my-search-highlight {
207
+ background-color: yellow;
208
+ color: black;
209
+ }
210
+ /* etc. */
211
+ ```
212
+
213
+ ## Public Methods
214
+
215
+ Instances of `PlacesAutocompleteJs` have the following public methods:
216
+
217
+ * **`clear()`**: Clears the input field and any visible suggestions, and refreshes the session token.
218
+ * **`destroy()`**: Removes event listeners and cleans up DOM elements created by the widget. Useful when the component is no longer needed (e.g., in SPAs when a view is unmounted).
219
+
220
+ ## Google Places API & Billing
221
+
222
+ * This library uses the Google Maps JavaScript API (specifically the Places library). Usage is subject to Google's terms and pricing.
223
+ * An API key enabled for the "Places API" (and "Maps JavaScript API") is required.
224
+ * The library uses **Session Tokens** automatically to group Autocomplete requests, which can lead to significant cost savings compared to per-request billing. See [Google's Session Token Pricing](https://developers.google.com/maps/documentation/places/web-service/usage-and-billing#session-pricing).
225
+ * Place Details requests (made when a suggestion is selected to get `displayName`, `formattedAddress`, etc.) are billed separately. The library currently fetches `displayName`, `formattedAddress`, and `addressComponents` by default. This can be expanded if needed, but be mindful of [Place Data Fields Pricing](https://developers.google.com/maps/documentation/javascript/usage-and-billing#data-pricing).
226
+
227
+ ## Contributing
228
+
229
+ Contributions are welcome! Please feel free to open an issue or submit a pull request.
230
+
231
+ ## License
232
+
233
+ [MIT](LICENSE)
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "places-autocomplete-js",
3
+ "license": "MIT",
4
+ "type": "module",
5
+ "version": "1.0.0",
6
+ "description": "A flexible and customisable vanilla JavaScript library leveraging the Google Maps Places (New) Autocomplete API. This library provides a user-friendly way to search for and retrieve detailed address information in any web application.",
7
+ "keywords": [
8
+ "place-autocomplete-js",
9
+ "google-places-api",
10
+ "google-places-autocomplete-api",
11
+ "autocomplete",
12
+ "google-maps",
13
+ "places-autocomplete",
14
+ "location",
15
+ "geocoding",
16
+ "address",
17
+ "address-input",
18
+ "input",
19
+ "search",
20
+ "new api"
21
+ ],
22
+ "homepage": "https://github.com/alexpechkarev/places-autocomplete-js#readme",
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/alexpechkarev/places-autocomplete-js.git"
26
+ },
27
+ "bugs": {
28
+ "url": "https://github.com/alexpechkarev/places-autocomplete-js/issues"
29
+ },
30
+ "author": {
31
+ "name": "Alexander Pechkarev",
32
+ "url": "https://github.com/alexpechkarev"
33
+ },
34
+ "files": [
35
+ "dist"
36
+ ],
37
+ "main": "./dist/PlacesAutocompleteJs.umd.cjs",
38
+ "module": "./dist/PlacesAutocompleteJs.js",
39
+ "exports": {
40
+ ".": {
41
+ "import": "./dist/PlacesAutocompleteJs.js",
42
+ "require": "./lib/PlacesAutocompleteJs.umd.cjs"
43
+ }
44
+ },
45
+
46
+ "scripts": {
47
+ "dev": "vite dev",
48
+ "build": "vite build",
49
+ "preview": "vite preview",
50
+ "lint": "eslint src/**/*.js"
51
+ },
52
+ "devDependencies": {
53
+ "eslint": "^9.26.0",
54
+ "vite": "^6.3.5",
55
+ "@tailwindcss/vite": "^4.1.6",
56
+ "tailwindcss": "^4.1.6",
57
+ "@tailwindcss/postcss": "^4.1.6",
58
+ "postcss": "^8.5.3"
59
+ },
60
+ "dependencies": {}
61
+ }