### Install via NPM or Yarn Source: https://geoapify.github.io/geocoder-autocomplete/quick-start Install the Geoapify Geocoder Autocomplete package using your preferred package manager. This is recommended for web applications and build systems. ```bash npm install @geoapify/geocoder-autocomplete # or yarn add @geoapify/geocoder-autocomplete ``` -------------------------------- ### Import Library and Stylesheet (NPM/Yarn) Source: https://geoapify.github.io/geocoder-autocomplete/quick-start Import the GeocoderAutocomplete library and its stylesheet in your project after installation. Choose from available styles like minimal.css or round-borders.css. ```javascript import { GeocoderAutocomplete } from '@geoapify/geocoder-autocomplete'; import '@geoapify/geocoder-autocomplete/styles/minimal.css'; // Available styles: minimal.css | minimal-dark.css | round-borders.css | round-borders-dark.css ``` -------------------------------- ### Subscribe to Request Start Event Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Use the `on` method to subscribe to the 'requestStart' event. The callback function receives the query string. This is useful for logging or displaying search status. ```javascript autocomplete.on('requestStart', (query) => { console.log('Searching for:', query); }); ``` -------------------------------- ### Example Response with Non-Verified House Number Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete-options This example shows a response object where the `housenumber` is marked as non-verified within the `nonVerifiedParts` array. ```json { "type": "Feature", "properties": { "address_line1": "Bürgermeister-Heinrich-Straße 60", "address_line2": "93077 Bad Abbach, Germany", "housenumber": "60", "nonVerifiedParts": [ "housenumber" ] } } ``` -------------------------------- ### Set Placeholder Text for Autocomplete Input Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete-options Use the `placeholder` option to define the hint text displayed in the input field before the user types. This improves usability by guiding expected input. ```javascript const autocomplete = new GeocoderAutocomplete( document.getElementById('autocomplete'), 'YOUR_API_KEY', { placeholder: 'Enter an address or city...' } ); ``` -------------------------------- ### Get Current Category with getCategory() Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Retrieve the currently active category object, if any. This is useful for determining the active category mode at runtime. ```javascript const current = autocomplete.getCategory(); console.log(current?.label); ``` -------------------------------- ### Include from CDN (UMD Build) Source: https://geoapify.github.io/geocoder-autocomplete/quick-start Include the prebuilt UMD module and stylesheet from a CDN for direct integration into an HTML page or CMS. This is ideal for static sites or when a build pipeline is not used. ```html ``` -------------------------------- ### Get Current Autocomplete Input Value Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Use getValue() to retrieve the current value of the autocomplete input. This is useful for form submissions or integration with other components. ```javascript const currentValue = autocomplete.getValue(); console.log(currentValue); ``` -------------------------------- ### GeocoderAutocomplete Configuration Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete-options Documentation for the configuration options available when initializing the GeocoderAutocomplete component. ```APIDOC ## GeocoderAutocompleteOptions ### Description The GeocoderAutocompleteOptions object allows you to configure the behavior, appearance, and search logic of the Geoapify Geocoder Autocomplete control. ### Parameters - **type** (LocationType) - Optional - Restrict suggestions to a specific type (e.g., city, postcode, street). - **lang** (string) - Optional - 2-character ISO 639-1 language code for returned results. - **limit** (number) - Optional - Maximum number of suggestions per query (Default: 5). - **placeholder** (string) - Optional - Placeholder text shown in the input. - **debounceDelay** (number) - Optional - Delay in ms before sending requests (Default: 100). - **filter** (Object/string) - Optional - Hard filter for geocoder results. - **bias** (Object) - Optional - Soft bias for geocoder results. - **skipIcons** (boolean) - Optional - Hide icons in the dropdown (Default: false). - **addDetails** (boolean) - Optional - Enrich selected result with details/geometry (Default: false). ### Request Example ```javascript const autocomplete = new GeocoderAutocomplete( document.getElementById('autocomplete'), 'YOUR_API_KEY', { type: 'city', lang: 'fr', placeholder: 'Enter an address or city...' } ); ``` ``` -------------------------------- ### Event Handling Methods (on, off, once) Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Methods to subscribe, unsubscribe, or listen once to component lifecycle and interaction events. ```APIDOC ## on(event, cb) ### Description Registers an event listener that will be called whenever the specified event is triggered. ### Parameters - **event** (GeocoderEventType) - Required - The name of the event. - **cb** (function) - Required - Callback function that receives event-specific data. ## off(event, cb) ### Description Removes a previously registered event listener. If no callback is provided, all listeners for that event are removed. ### Parameters - **event** (GeocoderEventType) - Required - The event name. - **cb** (function) - Optional - The specific callback function to remove. ## once(event, cb) ### Description Registers a one-time listener that is automatically unsubscribed after being triggered once. ### Parameters - **event** (GeocoderEventType) - Required - The event name. - **cb** (function) - Required - The callback function to execute once. ``` -------------------------------- ### Setting Postprocess Hook Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Lets you transform or format how suggestions appear in the dropdown list after they are fetched. ```APIDOC ## setPostprocessHook() ### Description Lets you transform or format how suggestions appear in the dropdown list after they are fetched. You can modify label text, append custom info, or apply your own formatting logic. ### Method `setPostprocessHook(fn?: (feature: any) => string | null)` ### Parameters #### Request Body - **fn** (function) - Optional - A function that takes each feature (GeoJSON object) and returns the display string. ### Request Example ```javascript autocomplete.setPostprocessHook((feature) => `${feature.properties.address_line1} (${feature.properties.country})` ); ``` ### Response This method does not return a value. It modifies the autocomplete instance's configuration. ``` -------------------------------- ### Activate Category Search Mode with selectCategory() Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Enable Places category search mode by providing category keys. This loads nearby results using the Places API. Category mode must be enabled via `addCategorySearch: true`. ```javascript await autocomplete.selectCategory('restaurant'); ``` -------------------------------- ### GeocoderAutocomplete Configuration Methods Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Methods for configuring the behavior and appearance of the autocomplete component. ```APIDOC ## Configuration Methods ### Description Methods to set language, result types, and display preferences. ### Methods - **setType**(type: 'country' | 'state' | 'city' | 'postcode' | 'street' | 'amenity' | null): void - Restrict result type. - **setLang**(lang: SupportedLanguage | null): void - Set language of results. - **setAddDetails**(addDetails: boolean): void - Toggle fetching extra geometry/details. - **setSkipIcons**(skipIcons: boolean): void - Show/hide icons in the dropdown. - **setAllowNonVerifiedHouseNumber**(value: boolean): void - Include non-verified house numbers. - **setAllowNonVerifiedStreet**(value: boolean): void - Include non-verified streets. - **setLimit**(limit: number): void - Max suggestions per query. - **setPlacesLimit**(limit: number): void - Page size for Places results. ``` -------------------------------- ### Handle Address Suggestions Source: https://geoapify.github.io/geocoder-autocomplete/quick-start Listen for the 'suggestions' event to process new address suggestions as the user types. This event provides an array of suggestion objects. ```javascript addressAutocomplete.on('suggestions', (suggestions) => { // Triggered whenever new suggestions are available console.log('Suggestions:', suggestions); }); ``` -------------------------------- ### Initialize Geocoder Autocomplete Source: https://geoapify.github.io/geocoder-autocomplete/quick-start Initialize the GeocoderAutocomplete with the container element, your API key, and optional geocoder options. Use 'autocomplete.GeocoderAutocomplete' if loaded from CDN. ```javascript import { GeocoderAutocomplete } from '@geoapify/geocoder-autocomplete'; // When installed via npm or yarn, GeocoderAutocomplete is imported directly. // When loaded from CDN, use "autocomplete.GeocoderAutocomplete" instead. const addressAutocomplete = new GeocoderAutocomplete( document.getElementById('autocomplete'), 'YOUR_API_KEY', { /* Geocoder options */ } ); addressAutocomplete.on('select', (location) => { // Handle selected location }); addressAutocomplete.on('suggestions', (suggestions) => { // Handle suggestion updates }); ``` -------------------------------- ### Subscribe to a One-Time Event Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Use the `once` method to register a listener that will be executed only one time. The listener is automatically unsubscribed after its first invocation. This is useful for initialization tasks. ```javascript autocomplete.once('opened', () => { console.log('Dropdown opened for the first time!'); }); ``` -------------------------------- ### Subscribe to Select Event Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Use the `on` method to subscribe to the 'select' event. The callback function receives the selected feature data. This is useful for responding to user selections. ```javascript autocomplete.on('select', (feature) => { console.log('User selected:', feature.properties.formatted); }); ``` -------------------------------- ### Initialize GeocoderAutocomplete Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Use this to create a functional address autocomplete field. It retrieves address suggestions in real-time as the user types. Ensure the container element has `position: relative` or `position: absolute`. ```javascript import { GeocoderAutocomplete } from '@geoapify/geocoder-autocomplete'; const container = document.getElementById('autocomplete'); const autocomplete = new GeocoderAutocomplete(container, 'YOUR_API_KEY', { placeholder: 'Enter address...', lang: 'en', limit: 5 }); ``` -------------------------------- ### Manual Request Methods Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Methods to manually trigger geocoder and place detail requests. ```APIDOC ## sendGeocoderRequest(value) ### Description Sends a manual geocoder API request with the provided value. ### Parameters - **value** (string) - Required - The query string to search for. ### Response - **Promise** - Resolving to a Geoapify Geocoder API response. ## sendPlaceDetailsRequest(feature) ### Description Fetches additional place details for a selected feature. ### Parameters - **feature** (any) - Required - The GeoJSON feature object returned from the autocomplete. ### Response - **Promise** - Resolving to a feature with additional details. ``` -------------------------------- ### enablePlacesLazyLoading Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete-options Controls whether the places list supports lazy loading, fetching additional results as the user scrolls for a smooth infinite-scroll experience. ```APIDOC ## enablePlacesLazyLoading ### Description Controls whether the places list supports lazy loading — automatically fetching additional results as the user scrolls. This allows users to explore more POIs without needing to manually trigger additional requests. ### Type `boolean` ### Default `true` ### Example ```javascript const autocomplete = new GeocoderAutocomplete( document.getElementById("autocomplete"), "YOUR_API_KEY", { addCategorySearch: true, showPlacesList: true, enablePlacesLazyLoading: true // load more places while scrolling } ); ``` Keep this enabled to provide a smooth, **infinite-scroll experience** for category search results. You can disable it if you prefer to manage pagination manually or display a limited set of results. ``` -------------------------------- ### Preprocess User Input Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Use `setPreprocessHook` to transform user input before it's sent to the Geoapify API. This is useful for sanitizing or normalizing input values. ```javascript autocomplete.setPreprocessHook((value) => value.trim().replace(/\s+/g, ' ')); ``` -------------------------------- ### Listen to request and selection events Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Use these event listeners to track geocoder request lifecycle and user selection changes. ```javascript autocomplete.on('requestStart', (query) => { console.log('Request started for:', query); }); autocomplete.on('requestEnd', (result) => { if (result.ok) console.log('Got results:', result.data.features.length); else console.error('Request failed:', result.error); }); autocomplete.on('select', (feature) => { if (feature) { console.log('Selected:', feature.properties.formatted); } else { console.log('Selection cleared'); } }); ``` -------------------------------- ### Dropdown State Management Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Methods to control the visibility and state of the autocomplete suggestions dropdown. ```APIDOC ## isOpen() ### Description Returns whether the dropdown list with suggestions is currently open. ### Response - **boolean** - true if the dropdown is visible, false otherwise. ## close() ### Description Closes the currently open suggestions or places dropdown. ## open() ### Description Reopens the dropdown list for the current input value, re-triggering a request for suggestions if necessary. ``` -------------------------------- ### Check if Dropdown is Open with isOpen() Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Determine if the dropdown list with suggestions is currently visible. Returns true if the dropdown is open, false otherwise. ```javascript if (autocomplete.isOpen()) { console.log('Dropdown is open'); } ``` -------------------------------- ### Reopen Suggestions Dropdown with open() Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Reopen the dropdown list for the current input value. This can re-trigger a request for suggestions if needed. ```javascript autocomplete.open(); ``` -------------------------------- ### Programmatically Select a Place Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Use `selectPlace` to select a place from the built-in list by its index. Set the index to `null` to clear the selection. This method only functions when `showPlacesList` is enabled. ```javascript autocomplete.selectPlace(0); // Select first place in list ``` -------------------------------- ### Autocomplete Configuration API Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Configure various aspects of the autocomplete functionality, including search type, language, details fetching, icon display, and verification settings. ```APIDOC ## setType() ### Description Restricts autocomplete results to a specific level of the address hierarchy. ### Method POST ### Endpoint /autocomplete ### Parameters #### Query Parameters - **type** (string) - Optional - Restricts results to one of the following: 'country', 'state', 'city', 'postcode', 'street', 'amenity', or null. ### Request Example ```json { "example": "autocomplete.setType('city');" } ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful configuration. #### Response Example ```json { "example": "Configuration updated successfully." } ``` ## setLang() ### Description Defines the language of returned suggestions. Set this to localize addresses or display place names in a user’s preferred language. ### Method POST ### Endpoint /autocomplete ### Parameters #### Query Parameters - **lang** (string) - Optional - The language code for returned suggestions (e.g., 'en', 'fr'). Defaults to English if translation is unavailable. ### Request Example ```json { "example": "autocomplete.setLang('fr');" } ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful configuration. #### Response Example ```json { "example": "Language set successfully." } ``` ## setAddDetails() ### Description Enables or disables fetching additional place details such as geometry or administrative boundaries. When true, it performs a secondary lookup via the Geoapify Place Details API. ### Method POST ### Endpoint /autocomplete ### Parameters #### Query Parameters - **addDetails** (boolean) - Required - Set to true to fetch additional details, false otherwise. ### Request Example ```json { "example": "autocomplete.setAddDetails(true);" } ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful configuration. #### Response Example ```json { "example": "Additional details setting updated." } ``` ## setSkipIcons() ### Description Toggles whether icons are shown in the dropdown list. Disabling icons can simplify or speed up rendering, especially in minimal UI designs. ### Method POST ### Endpoint /autocomplete ### Parameters #### Query Parameters - **skipIcons** (boolean) - Required - Set to true to skip displaying icons, false to display them. ### Request Example ```json { "example": "autocomplete.setSkipIcons(true);" } ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful configuration. #### Response Example ```json { "example": "Icon display setting updated." } ``` ## setAllowNonVerifiedHouseNumber() ### Description Allows the autocomplete to include non-verified house numbers in results. This is useful for areas with newly constructed buildings or incomplete datasets. ### Method POST ### Endpoint /autocomplete ### Parameters #### Query Parameters - **value** (boolean) - Required - Set to true to allow non-verified house numbers, false otherwise. ### Request Example ```json { "example": "autocomplete.setAllowNonVerifiedHouseNumber(true);" } ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful configuration. #### Response Example ```json { "example": "Non-verified house number setting updated." } ``` ## setAllowNonVerifiedStreet() ### Description Includes non-verified street names in autocomplete results. Ideal for emerging neighborhoods or developing regions where street data is still being updated. ### Method POST ### Endpoint /autocomplete ### Parameters #### Query Parameters - **value** (boolean) - Required - Set to true to include non-verified street names, false otherwise. ### Request Example ```json { "example": "autocomplete.setAllowNonVerifiedStreet(true);" } ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful configuration. #### Response Example ```json { "example": "Non-verified street setting updated." } ``` ## setLimit() ### Description Specifies the maximum number of autocomplete suggestions returned per query. ### Method POST ### Endpoint /autocomplete ### Parameters #### Query Parameters - **limit** (number) - Required - The maximum number of suggestions to return. Defaults to 5. ### Request Example ```json { "example": "autocomplete.setLimit(10);" } ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful configuration. #### Response Example ```json { "example": "Suggestion limit set successfully." } ``` ## setPlacesLimit() ### Description Sets the page size for the Places API results when category search is enabled. This controls how many places are fetched per request in the built-in or custom list. ### Method POST ### Endpoint /autocomplete ### Parameters #### Query Parameters - **limit** (number) - Required - The number of places to fetch per page. A smaller limit improves response speed, while a larger one provides a broader result set. ### Request Example ```json { "example": "autocomplete.setPlacesLimit(50);" } ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful configuration. #### Response Example ```json { "example": "Places limit set successfully." } ``` ``` -------------------------------- ### Setting Preprocess Hook Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Allows you to transform user input before sending a request to the Geoapify API. ```APIDOC ## setPreprocessHook() ### Description Allows you to transform user input before sending a request to the Geoapify API. Useful for sanitizing, normalizing, or adjusting values before autocomplete processing. ### Method `setPreprocessHook(fn?: (value: string) => string | null)` ### Parameters #### Request Body - **fn** (function) - Optional - A function that receives the input string and returns a transformed version. ### Request Example ```javascript autocomplete.setPreprocessHook((value) => value.trim().replace(/\s+/g, ' ')); ``` ### Response This method does not return a value. It modifies the autocomplete instance's configuration. ``` -------------------------------- ### GeocoderAutocomplete Control Methods Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Methods for programmatic control of the component state and manual requests. ```APIDOC ## Control Methods ### Description Methods to manage the dropdown state and trigger manual requests. ### Methods - **setValue**(value: string): void - Programmatically set input value. - **getValue**(): string - Read current input value. - **isOpen**(): boolean - Dropdown open state. - **close**(): void - Close dropdown. - **open**(): void - Open dropdown. - **sendGeocoderRequest**(value: string): Promise - Manually trigger geocoder request. - **sendPlaceDetailsRequest**(feature: any): Promise - Manually fetch details for a feature. ``` -------------------------------- ### Handle Places API and category mode events Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Use these event listeners when operating the component in category search mode to manage place requests and selections. ```javascript autocomplete.on('placesRequestStart', (category) => { console.log('Loading places for:', category.label); }); autocomplete.on('placesRequestEnd', (res) => { if (res.ok) console.log('Places loaded:', res.data.features.length); }); autocomplete.on('placeSelect', ({ place, index }) => { console.log(`Selected place #${index}:`, place.properties.name); }); ``` -------------------------------- ### selectPlace() Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Programmatically selects or clears a place from the built-in Places list. ```APIDOC ## selectPlace(index) ### Description Programmatically selects or clears a place from the built-in Places list. This only works when the built-in list (showPlacesList: true) is active. ### Parameters #### Path Parameters - **index** (number | null) - Required - The numeric index of the place to select, or null to clear. ### Request Example autocomplete.selectPlace(0); ``` -------------------------------- ### Request Customization Methods Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Methods to override default request behavior for place details and category searches. ```APIDOC ## setSendPlaceDetailsRequestFunc(fn) ### Description Overrides how place details are fetched after a user selects a result. ### Parameters - **fn** (function) - Required - A function that takes the selected feature and returns a Promise with enriched or custom details. ## setSendPlacesRequestFunc(fn) ### Description Overrides Places API category search requests. Used when category search is enabled. ### Parameters - **fn** (function) - Required - A function that takes category keys, pagination offset, and the autocomplete instance. Must return a Promise resolving to Geoapify Places-style results. ``` -------------------------------- ### Handling Non-Verified Address Components Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete-options Information on how Geoapify handles and how developers can manage non-verified address components in the response. ```APIDOC ## Working with Non-Verified Address Components ### Description In some cases, Geoapify may return non-verified address components, such as newly built streets or buildings not yet present in official databases. These components are still valid but carry a lower verification confidence. The library ensures that GPS coordinates remain accurate, even for non-verified entries. These fields are automatically marked with a `"non-verified"` CSS class, allowing developers to style or flag them in the UI. ### Handling Strategies 1. Display non-verified fields with a visual indicator (e.g., highlight in red or show a warning). 2. Allow users to edit or confirm the suggested address before submission. 3. Use the options `allowNonVerifiedHouseNumber` and `allowNonVerifiedStreet` to control how these cases are handled. ### Response Structure When non-verified elements are present, the result object includes a `nonVerifiedParts` array identifying which fields (like `street` or `housenumber`) are provisional. ### Response Example ```json { "type": "Feature", "properties": { "address_line1": "Bürgermeister-Heinrich-Straße 60", "address_line2": "93077 Bad Abbach, Germany", "housenumber": "60", "nonVerifiedParts": [ "housenumber" ] } } ``` ### UI Indication Non-verified fields are automatically marked with a `"non-verified"` CSS class in the rendered suggestions, enabling easy visual distinction. ``` -------------------------------- ### Enable Built-in Places List Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete-options Display a scrollable list of matching POIs directly under the autocomplete field when category search is active. Simplifies UI implementation. ```javascript const autocomplete = new GeocoderAutocomplete( document.getElementById("autocomplete"), "YOUR_API_KEY", { addCategorySearch: true, showPlacesList: true // display built-in places list } ); ``` -------------------------------- ### Add Autocomplete Container Source: https://geoapify.github.io/geocoder-autocomplete/quick-start Add a container element to your HTML where the autocomplete input will be rendered. Ensure the container has `position: relative` or `position: absolute` for correct dropdown placement. ```html
``` -------------------------------- ### Enable Lazy Loading for Places List Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete-options Allow the places list to fetch additional results as the user scrolls, providing an infinite-scroll experience. Keep enabled for smooth exploration. ```javascript const autocomplete = new GeocoderAutocomplete( document.getElementById("autocomplete"), "YOUR_API_KEY", { addCategorySearch: true, showPlacesList: true, enablePlacesLazyLoading: true // load more places while scrolling } ); ``` -------------------------------- ### Setting Suggestions Filter Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Defines a client-side filter function that post-processes suggestion results before they are displayed. ```APIDOC ## setSuggestionsFilter() ### Description Defines a client-side filter function that post-processes suggestion results before they are displayed. This is useful for removing or reordering results dynamically, without modifying the server response. ### Method `setSuggestionsFilter(fn?: (items: any[]) => any[] | null)` ### Parameters #### Request Body - **fn** (function) - Optional - A function that takes an array of suggestion items and returns a filtered or modified array. Pass `null` or omit to remove the filter. ### Request Example ```javascript autocomplete.setSuggestionsFilter((items) => items.filter(item => item.properties.country === 'Germany') ); ``` ### Response This method does not return a value. It modifies the autocomplete instance's configuration. ``` -------------------------------- ### Handle Address Selection Source: https://geoapify.github.io/geocoder-autocomplete/quick-start Listen for the 'select' event to handle the location selected by the user from the autocomplete dropdown. This event provides the selected location object. ```javascript addressAutocomplete.on('select', (location) => { // Triggered when the user selects a location from the dropdown console.log('Selected location:', location); }); ``` -------------------------------- ### Enable Fetching of Additional Place Details Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Use setAddDetails() to enable fetching of extra place information like geometry or administrative boundaries. This performs a secondary lookup via the Geoapify Place Details API. ```javascript autocomplete.setAddDetails(true); ``` -------------------------------- ### Set Maximum Number of Autocomplete Suggestions Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Use setLimit() to specify the maximum number of autocomplete suggestions returned per query. The default is 5. ```javascript autocomplete.setLimit(10); ``` -------------------------------- ### addCategorySearch Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete-options Enables category-based place search, allowing the input field to return points of interest (POIs) like restaurants, cafes, and hotels. ```APIDOC ## addCategorySearch ### Description Enables category-based place search in addition to address autocomplete. When activated, the input field can return points of interest (POIs) such as restaurants, cafes, hotels, gas stations, and more — powered by the Geoapify Places API. ### Type `boolean` ### Default `false` ### Example ```javascript const autocomplete = new GeocoderAutocomplete( document.getElementById("autocomplete"), "YOUR_API_KEY", { addCategorySearch: true, // allow searching by place categories placesFilter: { circle: { lon: -74.006, lat: 40.7128, radiusMeters: 5000 } // 5 km around New York } } ); ``` Category search is useful for implementing features such as: * “Find nearby” or “Search around me” * Location-based discovery for maps and local directories * Showing nearby amenities or business listings > **Tip:** Category search always works relative to a location or bounding area. Make sure to provide a **filter** or **bias** (for example, using user geolocation, IP location, or current map view) to focus the search. ``` -------------------------------- ### Autocomplete Utility API Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Utility methods for interacting with the autocomplete input value and managing search states. ```APIDOC ## setValue() ### Description Sets the value of the autocomplete input programmatically. This can be used to prefill the field or update it based on user interaction elsewhere in your app. ### Method POST ### Endpoint /autocomplete ### Parameters #### Request Body - **value** (string) - Required - The string value to set for the autocomplete input. ### Request Example ```json { "example": "autocomplete.setValue('New York, USA');" } ``` ### Response #### Success Response (200) - **message** (string) - Indicates the value was set successfully. #### Response Example ```json { "example": "Autocomplete value set successfully." } ``` ## getValue() ### Description Returns the current value of the autocomplete input. Useful for retrieving user input before form submission or integrating with external components. ### Method GET ### Endpoint /autocomplete/value ### Response #### Success Response (200) - **value** (string) - The current value of the autocomplete input. #### Response Example ```json { "example": "const currentValue = autocomplete.getValue();\nconsole.log(currentValue);" } ``` ## clearCategory() ### Description Exits category mode and resets the autocomplete list. ### Method POST ### Endpoint /autocomplete/clearCategory ### Response #### Success Response (200) - **message** (string) - Indicates the category was cleared successfully. #### Response Example ```json { "example": "Category cleared." } ``` ## resendPlacesRequestForMore() ### Description Fetches the next page for the Places list when category search is enabled. ### Method POST ### Endpoint /autocomplete/resendPlacesRequestForMore ### Parameters #### Query Parameters - **append** (boolean) - Optional - If true, appends results to the existing list; otherwise, replaces it. ### Response #### Success Response (200) - **message** (string) - Indicates the request for more places was successful. #### Response Example ```json { "example": "Next page of places loaded." } ``` ## getCategory() ### Description Returns the current category mode if active, otherwise null. ### Method GET ### Endpoint /autocomplete/category ### Response #### Success Response (200) - **category** (string | null) - The current category or null if not in category mode. #### Response Example ```json { "example": "const currentCategory = autocomplete.getCategory();" } ``` ## selectPlace() ### Description Selects or clears a place in the built-in list. This can be used to programmatically highlight or deselect a search result. ### Method POST ### Endpoint /autocomplete/selectPlace ### Parameters #### Request Body - **index** (number | null) - The index of the place to select, or null to clear the selection. ### Request Example ```json { "example": "autocomplete.selectPlace(0); // Select the first place\nautocomplete.selectPlace(null); // Clear selection" } ``` ### Response #### Success Response (200) - **message** (string) - Indicates the place selection was updated. #### Response Example ```json { "example": "Place selection updated." } ``` ## sendPlacesRequest() ### Description Loads Places for the current category when category search is enabled. ### Method POST ### Endpoint /autocomplete/sendPlacesRequest ### Response #### Success Response (200) - **message** (string) - Indicates the places request was sent successfully. #### Response Example ```json { "example": "Places request sent for current category." } ``` ``` -------------------------------- ### Enable Category Search with Places Filter Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete-options Activate category search to find points of interest (POIs) like restaurants or hotels. Requires a filter or bias to focus the search area. ```javascript const autocomplete = new GeocoderAutocomplete( document.getElementById("autocomplete"), "YOUR_API_KEY", { addCategorySearch: true, // allow searching by place categories placesFilter: { circle: { lon: -74.006, lat: 40.7128, radiusMeters: 5000 } // 5 km around New York } } ); ``` -------------------------------- ### showPlacesList Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete-options Controls whether a built-in places list is displayed under the autocomplete field when category search is enabled. This list shows matching POIs with names, addresses, and opening hours. ```APIDOC ## showPlacesList ### Description Controls whether a built-in places list is displayed under the autocomplete field when category search is enabled. When active, matching POIs (points of interest) are automatically shown in a scrollable list that includes names, addresses, and opening hours. ### Type `boolean` ### Default `false` ### Example ```javascript const autocomplete = new GeocoderAutocomplete( document.getElementById("autocomplete"), "YOUR_API_KEY", { addCategorySearch: true, showPlacesList: true // display built-in places list } ); ``` The built-in list simplifies implementation for most projects by providing a ready-to-use UI for category search results. If you prefer to create your own custom layout, set `showPlacesList: false` and handle results manually using the `places` event. ``` -------------------------------- ### Geocoder Autocomplete Events Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete A reference list of supported event names, their payloads, and trigger conditions for the Geocoder Autocomplete component. ```APIDOC ## Geocoder Autocomplete Events ### Description The Geocoder Autocomplete component supports various events that allow developers to respond to user interactions, geocoder lifecycle stages, and category-based place searches. These events are accessed via the `on()`, `off()`, and `once()` methods. ### Events Reference - **input** (string) - Fired when the user types in the autocomplete field. - **requestStart** (string) - Fired when a geocoder request is about to be sent. - **requestEnd** ({ ok: boolean, data?: any, error?: any }) - Fired when a geocoder response is received or failed. - **suggestions** (GeoJSON.Feature[]) - Fired when new autocomplete suggestions are available. - **select** (GeoJSON.Feature | null) - Fired when a user selects a suggestion or clears the selection. - **change** (GeoJSON.Feature | null) - Fired when the final value changes. - **placeDetailsRequestStart** (GeoJSON.Feature) - Fired when a Place Details request is initiated. - **placeDetailsRequestEnd** ({ ok: boolean, data?: GeoJSON.Feature, error?: any }) - Fired when a Place Details request is completed. - **opened** (void) - Fired when the dropdown is rendered. - **closed** (void) - Fired when the dropdown is closed. - **clear** ('address' | 'category') - Fired when the address or category field is cleared. - **placesRequestStart** (Category) - Fired when a Places API request starts in category search mode. - **placesRequestEnd** ({ ok: boolean, data?: any, error?: any }) - Fired when a Places API response is received. - **places** (GeoJSON.Feature[]) - Fired when the places list is updated in category mode. - **placeSelect** ({ place: GeoJSON.Feature, index: number }) - Fired when a place is selected from the built-in list. ``` -------------------------------- ### Set Autocomplete Suggestion Language Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Use setLang() to define the language for returned suggestions. If a translation is unavailable, results default to English. ```javascript autocomplete.setLang('fr'); // show results in French ``` -------------------------------- ### Include Non-Verified Street Names Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete-options Set `allowNonVerifiedStreet: true` to include suggestions for new or unconfirmed street names, beneficial for areas with developing address data. ```javascript const autocomplete = new GeocoderAutocomplete( document.getElementById('autocomplete'), 'YOUR_API_KEY', { allowNonVerifiedStreet: true // include approximate or new street names } ); ``` -------------------------------- ### Enable Category Search in Autocomplete Source: https://geoapify.github.io/geocoder-autocomplete/quick-start Set the `addCategorySearch` option to `true` to enable category-based search. This allows users to type category names and receive category suggestions alongside address results. Ensure you have a valid API key and configure any necessary filters like `placesFilter`. ```javascript const autocomplete = new GeocoderAutocomplete( document.getElementById("autocomplete"), "YOUR_API_KEY", { addCategorySearch: true, placesFilter: { circle: { lon: -74.006, lat: 40.7128, radiusMeters: 5000 }, // 5 km around New York City center }, } ); ``` -------------------------------- ### Postprocess Suggestion Display Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Customize how suggestions appear in the dropdown list using `setPostprocessHook`. This function modifies the display string for each fetched feature. ```javascript autocomplete.setPostprocessHook((feature) => `${feature.properties.address_line1} (${feature.properties.country})` ); ``` -------------------------------- ### Enable additional result details Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete-options Enriches selected results with extra information like geometry or boundaries via the Place Details API. ```javascript const autocomplete = new GeocoderAutocomplete( document.getElementById('autocomplete'), 'YOUR_API_KEY', { addDetails: true // include extra geometry and place information } ); ``` -------------------------------- ### Fetch Next Page of Places Results with resendPlacesRequestForMore() Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Retrieve the subsequent page of Places results for the active category. Optionally append new results to the existing list instead of replacing them. ```javascript await autocomplete.resendPlacesRequestForMore(true); ``` -------------------------------- ### Configure debounceDelay for GeocoderAutocomplete Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete-options Sets the delay in milliseconds before sending an API request to optimize performance and reduce redundant calls. ```javascript const autocomplete = new GeocoderAutocomplete( document.getElementById('autocomplete'), 'YOUR_API_KEY', { debounceDelay: 300 // wait 300ms before sending requests } ); ``` -------------------------------- ### Filter Suggestions Client-Side Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Define a client-side filter function with `setSuggestionsFilter` to post-process and modify suggestion results before display. Pass `null` or omit to remove the filter. ```javascript autocomplete.setSuggestionsFilter((items) => items.filter(item => item.properties.country === 'Germany') ); ``` -------------------------------- ### Category Search Management Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Methods for managing category-based searches within the autocomplete component. ```APIDOC ## selectCategory(category) ### Description Activates a Places category search mode. ### Parameters - **category** (Category | string | string[] | null) - Required - The category key(s) or a full Category object. ## clearCategory() ### Description Clears the current category selection and exits category mode. ## resendPlacesRequestForMore(append) ### Description Fetches the next page of Places results for the currently selected category. ### Parameters - **append** (boolean) - Optional - Whether to append results instead of replacing them. ## getCategory() ### Description Returns the currently active category. ``` -------------------------------- ### Configure Autocomplete to Suggest Cities Only Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete-options Use the `type` option to restrict suggestions to a specific location type, such as 'city'. This is useful for country or region selectors. ```javascript const autocomplete = new GeocoderAutocomplete( document.getElementById('autocomplete'), 'YOUR_API_KEY', { type: 'city' } ); ``` -------------------------------- ### Fetch Additional Place Details with sendPlaceDetailsRequest() Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Fetch extended place details for a selected feature. This method is typically used for OSM-based features that support additional metadata. ```javascript autocomplete.sendPlaceDetailsRequest(selectedFeature) .then(details => console.log(details.properties)); ``` -------------------------------- ### Set Page Size for Places API Results Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Use setPlacesLimit() to set the page size for Places API results when category search is enabled. This controls how many places are fetched per request. ```javascript autocomplete.setPlacesLimit(50); ``` -------------------------------- ### placesLimit Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete-options Specifies the maximum number of places retrieved per request when category search is enabled, controlling the page size of results. ```APIDOC ## placesLimit ### Description Specifies the maximum number of places retrieved per request when category search is enabled. This setting controls the page size of results in the built-in places list or your custom implementation. ### Type `number` ### Default `20` ### Example ```javascript const autocomplete = new GeocoderAutocomplete( document.getElementById("autocomplete"), "YOUR_API_KEY", { addCategorySearch: true, showPlacesList: true, placesLimit: 50 // fetch up to 50 places per request } ); ``` Adjust `placesLimit` to balance **performance** and **result variety** : * A smaller limit ensures faster responses. * A larger limit provides a broader overview of available places in one request. This setting is especially relevant when lazy loading is enabled. ``` -------------------------------- ### GeocoderAutocomplete Spatial Configuration Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete-options Configuration options for spatial filtering and biasing within the GeocoderAutocomplete constructor. ```APIDOC ## GeocoderAutocomplete Spatial Options ### Description Configure spatial constraints for the GeocoderAutocomplete component to either restrict results to a specific area (placesFilter) or prioritize results near a location (placesBias). ### Parameters #### placesFilter (object) - **circle** (ByCircleOptions) - Optional - Restricts search to a circular area. - **rect** (ByRectOptions) - Optional - Restricts search to a rectangular bounding box. - **place** (string) - Optional - Restricts search to a specific place identifier or GeoJSON geometry. #### placesBias (object) - **circle** (ByCircleOptions) - Optional - Prioritizes results within a circular area. - **rect** (ByRectOptions) - Optional - Prioritizes results within a rectangular bounding box. - **proximity** (ByProximityOptions) - Optional - Prioritizes results based on proximity to a coordinate. ### Request Example ```javascript const autocomplete = new GeocoderAutocomplete( document.getElementById("autocomplete"), "YOUR_API_KEY", { addCategorySearch: true, placesFilter: { circle: { lon: -74.006, lat: 40.7128, radiusMeters: 5000 } }, placesBias: { proximity: { lon: -118.2437, lat: 34.0522 } } } ); ``` ``` -------------------------------- ### Override Place Details Fetching with setSendPlaceDetailsRequestFunc Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Customize how place details are fetched after a user selects a result. This function allows you to return custom details or skip the default fetching mechanism. ```javascript autocomplete.setSendPlaceDetailsRequestFunc(async (feature) => { // Return custom details or skip return { ...feature, customInfo: 'Pre-fetched locally' }; }); ``` -------------------------------- ### Send Manual Geocoder Request with sendGeocoderRequest() Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Perform a manual geocoder API request with a given query string. Useful for custom workflows or testing purposes. ```javascript autocomplete.sendGeocoderRequest('Berlin, Germany') .then(result => console.log(result)); ``` -------------------------------- ### Include Non-Verified Street Names in Autocomplete Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Use setAllowNonVerifiedStreet() to include non-verified street names in results. This is useful for developing regions where street data is updated. ```javascript autocomplete.setAllowNonVerifiedStreet(true); ``` -------------------------------- ### Set Maximum Places Retrieved Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete-options Specify the maximum number of places to retrieve per request for category search. Controls the page size of results. ```javascript const autocomplete = new GeocoderAutocomplete( document.getElementById("autocomplete"), "YOUR_API_KEY", { addCategorySearch: true, showPlacesList: true, placesLimit: 50 // fetch up to 50 places per request } ); ``` -------------------------------- ### Configure Autocomplete for French Language Results Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete-options Set the `lang` option to a 2-character ISO 639-1 language code to localize autocomplete suggestions. The API falls back to English if the chosen language is unavailable. ```javascript const autocomplete = new GeocoderAutocomplete( document.getElementById('autocomplete'), 'YOUR_API_KEY', { lang: 'fr' // French } ); ``` -------------------------------- ### allowNonVerifiedStreet Option Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete-options Enables the inclusion of non-verified street names in address suggestions. This is beneficial for areas with new or unconfirmed streets. ```APIDOC ## Configuration Option: allowNonVerifiedStreet ### Description Allows the autocomplete to include non-verified street names in address suggestions. By default, the autocomplete returns only verified street data. However, enabling this option ensures that new or unconfirmed streets — often found in developing areas or new housing projects — can still appear in the search results. ### Type `boolean` ### Default `false` ### Example ```javascript const autocomplete = new GeocoderAutocomplete( document.getElementById('autocomplete'), 'YOUR_API_KEY', { allowNonVerifiedStreet: true // include approximate or new street names } ); ``` ### Use Case Use this option when your users need to find recently built or unofficial streets, especially in regions where address data is frequently updated or incomplete. ``` -------------------------------- ### skipSelectionOnArrowKey Option Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete-options Controls whether the input field's value updates when navigating through suggestions using arrow keys. When set to true, the input remains unchanged until a selection is confirmed. ```APIDOC ## Configuration Option: skipSelectionOnArrowKey ### Description Determines whether the input value changes while navigating suggestions using arrow keys. By default, the field text updates as users move through suggestions. Enabling this option prevents that behavior, keeping the input unchanged until the user confirms a selection. ### Type `boolean` ### Default `false` ### Example ```javascript const autocomplete = new GeocoderAutocomplete( document.getElementById('autocomplete'), 'YOUR_API_KEY', { skipSelectionOnArrowKey: true // don't change text when navigating with arrows } ); ``` ### Use Case Use `skipSelectionOnArrowKey` to avoid visual flickering or text changes in situations where users need to browse suggestions before selecting one explicitly (e.g., when using keyboard-only input). ``` -------------------------------- ### sendPlacesRequest() Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Triggers a Places API request for the currently active category and filters. ```APIDOC ## sendPlacesRequest() ### Description Triggers a Places API request for the currently active category and filters. This is the main method used internally for category search, but you can call it directly to reload results. ### Request Example await autocomplete.sendPlacesRequest(); ``` -------------------------------- ### Close Suggestions Dropdown with close() Source: https://geoapify.github.io/geocoder-autocomplete/api-reference/geocoder-autocomplete Manually close the currently open suggestions or places dropdown. Useful for hiding the list after specific user interactions. ```javascript autocomplete.close(); ``` -------------------------------- ### Reverse Geocode (My Location) Placeholder Source: https://geoapify.github.io/geocoder-autocomplete/demo/address-form-search-plus-map/index.html This is a placeholder for the reverse geocoding functionality when using the user's current location. No specific code is provided in this section. ```plaintext ```