places-autocomplete-svelte 2.2.16 → 2.2.17

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.
package/README.md CHANGED
@@ -53,110 +53,69 @@ yarn add places-autocomplete-svelte
53
53
 
54
54
  ## Usage
55
55
 
56
- Provide your Google Maps API key to the component. It will automatically handle loading the required `places` library.
56
+ The `PlaceAutocomplete` component is designed for simplicity. Here’s the minimum required to get it working:
57
57
 
58
- ```javascript
59
- <script lang="ts">
60
- import { PlaceAutocomplete } from 'places-autocomplete-svelte';
61
- import type { PlaceResult, ComponentOptions, RequestParams } from 'places-autocomplete-svelte/interfaces';
62
58
 
63
- // Get API Key securely (e.g., from environment variables)
64
- const PUBLIC_GOOGLE_MAPS_API_KEY = import.meta.env.VITE_PUBLIC_GOOGLE_MAPS_API_KEY;
59
+ ```javascript
60
+ // In your +page.svelte or a parent component
65
61
 
66
- // --- Event Handlers ---
67
- let fullResponse: PlaceResult | null = $state(null);
68
- let placesError = $state('');
62
+ <script lang="ts">
63
+ import { PlaceAutocomplete } from 'places-autocomplete-svelte';
64
+ import type { PlaceResult } from 'places-autocomplete-svelte/interfaces';
69
65
 
70
- const handleResponse = (response: PlaceResult) => {
71
- console.log('Place Selected:', response);
72
- fullResponse = response;
73
- placesError = ''; // Clear previous errors
74
- };
66
+ // Get API Key securely (e.g., from environment variables)
67
+ const PUBLIC_GOOGLE_MAPS_API_KEY = import.meta.env.VITE_PUBLIC_GOOGLE_MAPS_API_KEY;
75
68
 
76
- const handleError = (error: string) => {
77
- console.error('Places Autocomplete Error:', error);
78
- placesError = error;
79
- fullResponse = null; // Clear previous results
80
- };
69
+ // --- Handle Component Response ---
70
+ const handleResponse = (response: PlaceResult) => {
71
+ console.log('Place Selected:', response.formattedAddress);
72
+ };
81
73
 
82
- // --- Configuration (Optional) ---
83
- const requestParams: Partial<RequestParams> = $state({
84
- region: 'GB',
85
- language: 'en-GB',
86
- });
87
- const fetchFields: string[] = $state(['formattedAddress', 'addressComponents', 'displayName']);
88
- const options: Partial<ComponentOptions> = $state({
89
- placeholder: 'Start typing your address...',
90
- debounce: 200,
91
- classes: {
92
- input: 'my-custom-input-class border-blue-500',
93
- highlight: 'bg-yellow-200 text-black',
94
- },
95
- clear_input: false,
96
- });
74
+ // --- Handle Component Errors ---
75
+ const handleError = (error: string) => {
76
+ console.error('Error:', error);
77
+ };
97
78
  </script>
98
79
 
99
- {#if placesError}
100
- <div class="error-message" role="alert">
101
- Error: {placesError}
102
- </div>
103
- {/if}
104
-
105
- <PlaceAutocomplete
106
- {PUBLIC_GOOGLE_MAPS_API_KEY}
107
- {requestParams}
108
- {fetchFields}
109
- {options}
110
- onResponse={handleResponse}
111
- onError={handleError}
112
- />
113
-
114
- {#if fullResponse}
115
- <h2>Selected Place Details:</h2>
116
- <pre>{JSON.stringify(fullResponse, null, 2)}</pre>
117
- {/if}
118
-
119
- <style>
120
- :global(.my-custom-input-class) {
121
- padding: 0.75rem;
122
- border-radius: 0.25rem;
123
- width: 100%;
124
- }
125
- .error-message {
126
- color: red;
127
- margin-bottom: 1rem;
128
- }
129
- </style>
80
+ <!-- Add the component to your page -->
81
+ <PlaceAutocomplete {onResponse} {onError} {PUBLIC_GOOGLE_MAPS_API_KEY} />
130
82
  ```
131
83
 
132
84
  ### Advanced: Using with other Google Maps Libraries
133
85
 
134
- You can reuse the shared Google Maps loader created by the `PlaceAutocomplete` component to load other libraries (like `maps`). Because the loader instance is shared, you can access it from any other component to load additional libraries without causing conflicts.
86
+ The `PlaceAutocomplete` component intelligently manages the Google Maps loader. For simple use cases, it handles loading automatically. However, if you need to use other Google Maps libraries (like `maps` or `marker`) on the same page, you should initialise the loader once in a parent component (`+page.svelte` or `+layout.svelte`). This prevents conflicts and ensures all libraries are loaded efficiently.
87
+
88
+ The component provides helper functions (`setGMapsContext`, `getGMapsContext`, `initialiseGMaps`) to manage this.
89
+
90
+ Here is how you would set it up in your `+page.svelte`:
135
91
 
136
- The `PlaceAutocomplete` component only loads the `places` library by default.
137
92
  ```javascript
138
- // In a parent component, e.g., src/routes/+page.svelte
93
+ // src/routes/+page.svelte
139
94
  <script lang="ts">
140
- import { onMount } from 'svelte';
141
- import { getGMapsLoader } from 'places-autocomplete-svelte/gmaps';
142
- import PlaceAutocomplete from '$lib/PlaceAutocomplete.svelte';
143
-
144
- const PUBLIC_GOOGLE_MAPS_API_KEY = import.meta.env.VITE_PUBLIC_GOOGLE_MAPS_API_KEY;
145
-
146
- // Pre-initialise the loader with all libraries needed for this page.
147
- onMount(async () => {
148
- const loader = getGMapsLoader(PUBLIC_GOOGLE_MAPS_API_KEY);
149
- const { Map } = await loader.importLibrary('maps');
150
- ...
151
- });
95
+ import { onMount } from 'svelte';
96
+ import { browser } from '$app/environment';
97
+ import { PlaceAutocomplete } from 'places-autocomplete-svelte';
98
+ import { initialiseGMaps, setGMapsContext, getGMapsContext } from 'places-autocomplete-svelte/gmaps';
99
+
100
+ // 1. Set the context for Google Maps. This should be done in the script's top-level scope.
101
+ setGMapsContext();
102
+
103
+ // 2. If we are in the browser, trigger the asynchronous loading process.
104
+ if (browser) {
105
+ initialiseGMaps({
106
+ key: import.meta.env.VITE_PUBLIC_GOOGLE_MAPS_API_KEY,
107
+ v: 'weekly'
108
+ }).catch((error: any) => {
109
+ // ... handle error (already logged in initialiseGMaps)
110
+ });
111
+ }
112
+
113
+ // ... rest of your component logic
152
114
  </script>
153
115
 
154
- <!-- The component will now use the loader you created above -->
155
- <PlaceAutocomplete
156
- {PUBLIC_GOOGLE_MAPS_API_KEY}
157
- onResponse={...}
158
- onError={...}
159
- />
116
+ <!-- The PlaceAutocomplete component will automatically use the context -->
117
+ <!-- You do NOT need to pass the `PUBLIC_GOOGLE_MAPS_API_KEY` prop to the component if you initialise the loader in a parent component.-->
118
+ <PlaceAutocomplete onResponse={...} onError={...} />
160
119
 
161
120
  <!-- You can now use other Google Maps services, e.g., a map -->
162
121
  <div id="map"></div>
@@ -189,7 +148,7 @@ This component is built to be accessible and follows the [WAI-ARIA Authoring Pra
189
148
 
190
149
  | Prop | Type | Required | Default | Description |
191
150
  | :--- | :--- | :--- | :--- | :--- |
192
- | `PUBLIC_GOOGLE_MAPS_API_KEY` | `string` | Yes | - | Your restricted Google Maps API Key. |
151
+ | `PUBLIC_GOOGLE_MAPS_API_KEY` | `string` | Yes | - | Your restricted Google Maps API Key. Not required if the loader has been initialised in a parent component. |
193
152
  | `fetchFields` | `string[]` | No | `['formattedAddress', 'addressComponents']` | Place Data Fields to request. **Affects API cost.** |
194
153
  | `requestParams` | `Partial<RequestParams>` | No | `{ inputOffset: 3, ... }` | Parameters for the Autocomplete API request. |
195
154
  | `options` | `Partial<ComponentOptions>` | No | `{ debounce: 100, ... }` | Options to control component behavior and appearance. |
@@ -1,6 +1,7 @@
1
1
  <script lang="ts">
2
2
  import { onMount } from 'svelte';
3
3
  import type { PlaceResult, Props } from './interfaces.js';
4
+ import { getGMapsContext, hasGMapsContext, importLibrary, initialiseGMapsNoContext, type GMapsContext } from './gmaps.js';
4
5
  import {
5
6
  validateOptions,
6
7
  validateRequestParams,
@@ -10,7 +11,13 @@
10
11
  debounce
11
12
  } from './helpers.js';
12
13
 
13
- import { getGMapsLoader, type GMapsLoaderType } from './gmaps.js';
14
+
15
+ let gmaps: GMapsContext | undefined;
16
+ // Get the context synchronously. This is safe.
17
+ if (hasGMapsContext()) {
18
+ gmaps = getGMapsContext();
19
+ }
20
+
14
21
 
15
22
 
16
23
  let {
@@ -18,7 +25,7 @@
18
25
  * By default using SKU: Place Detals (Location Only) - 0.005 USD per each
19
26
  * @see https://developers.google.com/maps/documentation/javascript/usage-and-billing#location-placedetails
20
27
  */
21
- PUBLIC_GOOGLE_MAPS_API_KEY,
28
+ PUBLIC_GOOGLE_MAPS_API_KEY='',
22
29
  fetchFields,
23
30
  options,
24
31
  onResponse = $bindable((response: PlaceResult) => {}),
@@ -36,7 +43,6 @@
36
43
  fetchFields = validateFetchFields(fetchFields);
37
44
  //console.log(fetchFields);
38
45
 
39
-
40
46
  let kbdAction = $state(''); // 'up', 'down', or 'escape'
41
47
 
42
48
  // Local variables
@@ -44,7 +50,6 @@
44
50
  let currentSuggestion = $state(-1);
45
51
  let results: any[] = $state([]);
46
52
  let placesApi: { [key: string]: any } = {};
47
- let loader: GMapsLoaderType;
48
53
 
49
54
  //https://developers.google.com/maps/documentation/javascript/reference/autocomplete-data
50
55
  // validate requestParams
@@ -213,6 +218,8 @@
213
218
  * Initialize the Google Maps JavaScript API Loader.
214
219
  */
215
220
  onMount(async (): Promise<void> => {
221
+
222
+
216
223
  if (isDefaultOnResponse) {
217
224
  console.warn(
218
225
  'PlaceAutocomplete: The `onResponse` callback has not been provided. Selected place data will not be handled. See documentation for usage.'
@@ -224,16 +231,26 @@
224
231
  }
225
232
 
226
233
  try {
227
- loader = getGMapsLoader(PUBLIC_GOOGLE_MAPS_API_KEY);
228
- } catch (e: any) {
229
- onError(
230
- (e.name || 'An error occurred') + ' - ' + (e.message || 'Error loading Google Maps API')
231
- );
232
- }
234
+ // Await the promise that was stored in the context by the parent.
235
+ // If the parent has already finished, this resolves immediately.
236
+ // If the parent is still loading, this will wait.
237
+ if(typeof gmaps !== 'undefined' && gmaps) {
238
+ await gmaps?.initializationPromise;
239
+ }else{
240
+
241
+ // Check if the API key is provided
242
+ if(PUBLIC_GOOGLE_MAPS_API_KEY === '' || !PUBLIC_GOOGLE_MAPS_API_KEY) {
243
+ throw new Error('Google Maps API key is required. Please provide a valid API key.');
244
+ }
245
+
246
+ // No context available, initialize without context
247
+ // This will load the Google Maps script
248
+ // and set up the necessary objects
249
+ // for places API usage.
250
+ await initialiseGMapsNoContext({key: PUBLIC_GOOGLE_MAPS_API_KEY, 'v': 'weekly'});
251
+ }
233
252
 
234
- try {
235
- const { AutocompleteSessionToken, AutocompleteSuggestion } =
236
- await loader.importLibrary('places');
253
+ const { AutocompleteSessionToken, AutocompleteSuggestion } = await importLibrary('places');
237
254
 
238
255
  placesApi.AutocompleteSessionToken = AutocompleteSessionToken;
239
256
  placesApi.AutocompleteSuggestion = AutocompleteSuggestion;
package/dist/gmaps.d.ts CHANGED
@@ -1,11 +1,34 @@
1
- import * as GMaps from '@googlemaps/js-api-loader';
1
+ import { type Writable } from 'svelte/store';
2
+ import { importLibrary, type APIOptions } from "@googlemaps/js-api-loader";
3
+ interface GMapsContext {
4
+ isInitialized: Writable<boolean>;
5
+ error: Writable<Error | null>;
6
+ initializationPromise: Promise<void> | null;
7
+ }
8
+ export type { GMapsContext, APIOptions };
2
9
  /**
3
- * Defines the shape of the context object that will be shared.
4
- * This can be expanded if you need to share more than just the loader.
10
+ * Creates and sets the Google Maps context with writable stores.
11
+ * This is synchronous and should be called once in a top-level component's script.
5
12
  */
6
- export type GMapsLoaderType = GMaps.Loader;
13
+ export declare function setGMapsContext(): void;
7
14
  /**
8
- * Gets the Google Maps Loader instance from Svelte's context.
9
- * @returns {typeof Loader}
15
+ * Retrieves the shared Google Maps context.
16
+ * @returns {GMapsContext} The stores for initialization status and errors.
10
17
  */
11
- export declare const getGMapsLoader: (PUBLIC_GOOGLE_MAPS_API_KEY: string, version?: string | undefined) => GMaps.Loader;
18
+ export declare function getGMapsContext(): GMapsContext;
19
+ export declare function hasGMapsContext(): boolean;
20
+ /**
21
+ * Asynchronously initializes the Google Maps loader using the provided context.
22
+ * This function is idempotent and safe to be called multiple times.
23
+ * @param context - The GMapsContext object.
24
+ * @param options - The options for the JS API loader, including your API key.
25
+ * @returns {Promise<void>}
26
+ */
27
+ export declare function initialiseGMaps(options: APIOptions): Promise<void>;
28
+ /**
29
+ * Initializes the Google Maps API without using the context.
30
+ * @param options The options for the JS API loader, including your API key.
31
+ * @returns A promise that resolves when the API is initialized.
32
+ */
33
+ export declare function initialiseGMapsNoContext(options: APIOptions): Promise<void>;
34
+ export { importLibrary };
package/dist/gmaps.js CHANGED
@@ -1,23 +1,87 @@
1
- import { getContext, setContext, hasContext } from 'svelte';
2
- import * as GMaps from '@googlemaps/js-api-loader';
3
- const { Loader } = GMaps;
1
+ import { getContext, setContext } from 'svelte';
2
+ import { writable, get } from 'svelte/store';
3
+ import { setOptions, importLibrary } from "@googlemaps/js-api-loader";
4
+ const LOADER_CONTEXT_KEY = Symbol('gmaps-loader');
4
5
  /**
5
- * A unique key for setting and getting the Google Maps Loader instance from Svelte's context.
6
- * This allows multiple components to share a single loader instance.
6
+ * Creates and sets the Google Maps context with writable stores.
7
+ * This is synchronous and should be called once in a top-level component's script.
7
8
  */
8
- const gmapsContextKey = Symbol('pacgmaps');
9
+ export function setGMapsContext() {
10
+ // Only set the context if it doesn't already exist.
11
+ if (getContext(LOADER_CONTEXT_KEY))
12
+ return;
13
+ setContext(LOADER_CONTEXT_KEY, {
14
+ isInitialized: writable(false),
15
+ error: writable(null),
16
+ initializationPromise: null, // Will be set by the loader function
17
+ });
18
+ }
9
19
  /**
10
- * Gets the Google Maps Loader instance from Svelte's context.
11
- * @returns {typeof Loader}
20
+ * Retrieves the shared Google Maps context.
21
+ * @returns {GMapsContext} The stores for initialization status and errors.
12
22
  */
13
- export const getGMapsLoader = (PUBLIC_GOOGLE_MAPS_API_KEY, version) => {
14
- version = version || 'weekly';
15
- if (!hasContext(gmapsContextKey)) {
16
- const loader = new Loader({
17
- apiKey: PUBLIC_GOOGLE_MAPS_API_KEY,
18
- version: version,
19
- });
20
- setContext(gmapsContextKey, loader);
23
+ export function getGMapsContext() {
24
+ const context = getContext(LOADER_CONTEXT_KEY);
25
+ if (!context) {
26
+ throw new Error('Google Maps context not found. Call setGMapsContext in a parent component.');
21
27
  }
22
- return getContext(gmapsContextKey);
23
- };
28
+ return context;
29
+ }
30
+ export function hasGMapsContext() {
31
+ const context = getContext(LOADER_CONTEXT_KEY);
32
+ return !!context;
33
+ }
34
+ /**
35
+ * Asynchronously initializes the Google Maps loader using the provided context.
36
+ * This function is idempotent and safe to be called multiple times.
37
+ * @param context - The GMapsContext object.
38
+ * @param options - The options for the JS API loader, including your API key.
39
+ * @returns {Promise<void>}
40
+ */
41
+ export async function initialiseGMaps(options) {
42
+ // Get the context internally
43
+ const context = getGMapsContext();
44
+ // If the promise already exists, just await it. Don't re-initialize.
45
+ if (context.initializationPromise) {
46
+ return context.initializationPromise;
47
+ }
48
+ // If it's already marked as initialized (e.g., from a previous page navigation), resolve immediately.
49
+ if (get(context.isInitialized)) {
50
+ return Promise.resolve();
51
+ }
52
+ // Create the promise and store it in the context object.
53
+ context.initializationPromise = new Promise((resolve, reject) => {
54
+ try {
55
+ setOptions(options); // Await the setOptions which returns a promise
56
+ context.isInitialized.set(true);
57
+ resolve();
58
+ }
59
+ catch (e) {
60
+ const error = e instanceof Error ? e : new Error(String(e));
61
+ context.error.set(error);
62
+ console.error("Failed to set Google Maps API options.", error);
63
+ reject(error);
64
+ }
65
+ });
66
+ return context.initializationPromise;
67
+ }
68
+ /**
69
+ * Initializes the Google Maps API without using the context.
70
+ * @param options The options for the JS API loader, including your API key.
71
+ * @returns A promise that resolves when the API is initialized.
72
+ */
73
+ export function initialiseGMapsNoContext(options) {
74
+ return new Promise((resolve, reject) => {
75
+ try {
76
+ setOptions(options);
77
+ resolve();
78
+ }
79
+ catch (e) {
80
+ const error = e instanceof Error ? e : new Error(String(e));
81
+ console.error("Failed to set Google Maps API options.", error);
82
+ reject(error);
83
+ }
84
+ });
85
+ }
86
+ // Re-export importLibrary for components to use.
87
+ export { importLibrary };
@@ -63,7 +63,7 @@ export interface FormattedAddress {
63
63
  postcode: string;
64
64
  }
65
65
  export interface Props {
66
- PUBLIC_GOOGLE_MAPS_API_KEY: string;
66
+ PUBLIC_GOOGLE_MAPS_API_KEY?: string;
67
67
  options?: ComponentOptions;
68
68
  fetchFields?: string[];
69
69
  libraries?: string[];
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "places-autocomplete-svelte",
3
3
  "license": "MIT",
4
- "version": "2.2.16",
4
+ "version": "2.2.17",
5
5
  "description": "A flexible, accessible, and secure Svelte component leveraging the Google Maps Places Autocomplete API (New) to provide a user-friendly way to search for and retrieve detailed address information.",
6
6
  "keywords": [
7
7
  "svelte",
@@ -55,7 +55,7 @@
55
55
  "./gmaps": {
56
56
  "types": "./dist/gmaps.d.ts",
57
57
  "svelte": "./dist/gmaps.js"
58
- },
58
+ },
59
59
  ".": {
60
60
  "types": "./dist/index.d.ts",
61
61
  "svelte": "./dist/index.js",
@@ -75,38 +75,38 @@
75
75
  "svelte": "^5.0.0"
76
76
  },
77
77
  "devDependencies": {
78
- "@sveltejs/adapter-auto": "^6.1.0",
79
- "@sveltejs/adapter-cloudflare": "^7.2.2",
80
- "@sveltejs/kit": "^2.36.1",
81
- "@sveltejs/package": "^2.5.0",
82
- "@sveltejs/vite-plugin-svelte": "^6.1.3",
83
- "@tailwindcss/postcss": "^4.1.12",
84
- "@tailwindcss/typography": "^0.5.16",
85
- "@tailwindcss/vite": "^4.1.12",
78
+ "@sveltejs/adapter-auto": "^6.1.1",
79
+ "@sveltejs/adapter-cloudflare": "^7.2.4",
80
+ "@sveltejs/kit": "^2.46.4",
81
+ "@sveltejs/package": "^2.5.4",
82
+ "@sveltejs/vite-plugin-svelte": "^6.2.1",
83
+ "@tailwindcss/postcss": "^4.1.14",
84
+ "@tailwindcss/typography": "^0.5.19",
85
+ "@tailwindcss/vite": "^4.1.14",
86
86
  "@types/eslint": "^9.6.1",
87
87
  "@types/google.maps": "^3.58.1",
88
- "@types/node": "^24.3.0",
88
+ "@types/node": "^24.7.1",
89
89
  "autoprefixer": "^10.4.21",
90
- "eslint": "^9.34.0",
90
+ "eslint": "^9.37.0",
91
91
  "eslint-config-prettier": "^10.1.8",
92
- "eslint-plugin-svelte": "^3.11.0",
93
- "globals": "^16.3.0",
92
+ "eslint-plugin-svelte": "^3.12.4",
93
+ "globals": "^16.4.0",
94
94
  "postcss": "^8.5.6",
95
95
  "prettier": "^3.6.2",
96
96
  "prettier-plugin-svelte": "^3.4.0",
97
- "publint": "^0.3.12",
98
- "svelte": "^5.38.2",
99
- "svelte-check": "^4.3.1",
100
- "tailwindcss": "^4.1.12",
97
+ "publint": "^0.3.14",
98
+ "svelte": "^5.39.11",
99
+ "svelte-check": "^4.3.3",
100
+ "tailwindcss": "^4.1.14",
101
101
  "tslib": "^2.8.1",
102
- "typescript": "^5.9.2",
103
- "typescript-eslint": "^8.40.0",
104
- "vite": "^7.1.3"
102
+ "typescript": "^5.9.3",
103
+ "typescript-eslint": "^8.46.0",
104
+ "vite": "^7.1.9"
105
105
  },
106
106
  "svelte": "./dist/index.js",
107
107
  "types": "./dist/PlaceAutocomplete.svelte.d.ts",
108
108
  "type": "module",
109
109
  "dependencies": {
110
- "@googlemaps/js-api-loader": "^1.16.10"
110
+ "@googlemaps/js-api-loader": "^2.0.1"
111
111
  }
112
112
  }