Learn how to search for an address with autosuggest using the geocoding service.
Autosuggest, also known as autocomplete, is a feature that predicts and displays location-based suggestions as a user types into a search box. In this tutorial, you use ArcGIS REST JS to access the geocoding service. You also create an input control to accept text and suggest address results. When a suggestion is selected, a pop-up will appear with the name, location, and address, and the map will pan to it.
Prerequisites
An ArcGIS Location Platform or ArcGIS Online account.
Steps
Get the starter app
Select a type of authentication below and follow the steps to create a new application.
Set up authentication
Create developer credentials in your portal for the type of authentication you selected.
Set developer credentials
Use the API key or OAuth developer credentials so your application can access location services.
Add references to ArcGIS REST JS
-
In the
<head
element, add references to the ArcGIS REST JS> request
andgeocoding
libraries.Use dark colors for code blocks <script src=https://unpkg.com/maplibre-gl@5.6.0/dist/maplibre-gl.js></script> <link href=https://unpkg.com/maplibre-gl@5.6.0/dist/maplibre-gl.css rel="stylesheet" /> <script src="https://unpkg.com/@esri/arcgis-rest-request@4/dist/bundled/request.umd.js"></script> <script src="https://unpkg.com/@esri/arcgis-rest-geocoding@4/dist/bundled/geocoding.umd.js"></script>
Update the map
A navigation basemap layer is typically used in geocoding and routing applications. Update the basemap layer to use arcgis/navigation
.
-
Update the basemap and initialize the map to center on the coordinates
[-123.102, 49.234]
with a zoom level of11
. This will center the map on Vancouver.Use dark colors for code blocks const basemapEnum = "arcgis/navigation"; const map = new maplibregl.Map({ container: "map", style: `https://basemapstyles-api.arcgis.com/arcgis/rest/services/styles/v2/styles/${basemapEnum}?token=${accessToken}`, zoom: 11, center: [-123.102, 49.234] // Vancouver });
Create geocoding controls
Create an HTML <div
containing an <input
for typing an address and a <button
to clear the input. Implement this <div
as a as a Map
control using the IControl interface. Then, in the <body
of your HTML, add a <ul
element to display address suggestions as the user types.
-
In the
<body
of your HTML, add a> <ul
element with the id> suggestions
.Use dark colors for code blocks <div id="map"></div> <ul id="suggestions"></ul>
-
Create a
Geocode
class with anControl on
function. Inside, create aAdd <div
element with an> <input
and a> <button
inside. Then, add the> geocode
element to theControl top-left
of the view.Use dark colors for code blocks class GeocodeControl { onAdd(map) { const template = document.createElement("template"); template.innerHTML = ` <div id="geocode-container"> <input id="geocode-input" class="maplibregl-ctrl" type="text" placeholder="Type an address, e.g. 200 Riverside Dr, Vancouver" autocomplete="off" /> <button id="clear-button" class="maplibregl-ctrl">×</button> </div> `; return template.content; } } map.addControl(new GeocodeControl(), "top-left");
-
Add styling to the controls.
Use dark colors for code blocks <style> html, body, #map { padding: 0; margin: 0; height: 100%; width: 100%; font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: #323232; } #geocode-container { display: flex; margin: 20px; font-size: 16px; } #geocode-input { margin: 0 2px 0 0; padding: 4px 8px; width: 40vw; } #clear-button { border: none; color: #666; cursor: pointer; position: absolute; right: 30px; bottom: 25px; background-color: #fff; } #suggestions { display: none; position: absolute; top: 50px; left: 20px; background: white; list-style: none; padding: 0; margin: 0; width: 40vw; } #suggestions li { padding: 6px 8px; border: 1px solid transparent; box-sizing: border-box; } #suggestions li:hover { background-color: #f0f0f0; } #suggestions li.selected { border-color: #6d29cc; } </style>
-
Set up interactivity for the geocoding controls by doing the following:
- Handling hover styles.
- Enabling keyboard navigation.
- Managing suggestion visibility with clear and outside-click actions.
Use dark colors for code blocks const suggestionsList = document.getElementById("suggestions"); let selectedIndex = -1; function updateSelection(items) { items.forEach((item, i) => item.classList.toggle("selected", i === selectedIndex)); } input.addEventListener("keydown", (e) => { const items = suggestionsList.querySelectorAll("li"); if (e.key === "ArrowDown") { if (selectedIndex < items.length - 1) selectedIndex++; } else if (e.key === "ArrowUp") { if (selectedIndex > 0) selectedIndex--; } else if (e.key === "Enter" && selectedIndex >= 0) { items[selectedIndex].click(); } updateSelection(items); }); document.getElementById("clear-button").addEventListener("click", () => { input.value = ""; popup.remove(); }); document.addEventListener("click", (e) => { if (!document.getElementById("geocode-container").contains(e.target)) { suggestionsList.style.display = "none"; } });
Get address suggestions
Use the suggest
method from the geocoding service to fetch location suggestions as user types.
-
Add an input event handler to capture text as the user types. Reset the selection index and hide suggestions when the input is empty.
Use dark colors for code blocks input.addEventListener("input", () => { selectedIndex = -1; const text = input.value; if (!text) return suggestions.style.display = "none"; });
-
Use the
suggest
method to fetch location suggestions as the user types, then display them in a list. For each suggestion, create an<li
element, append it to the suggestions list, and make the list visible.> Use dark colors for code blocks input.addEventListener("input", () => { selectedIndex = -1; const text = input.value; if (!text) return suggestions.style.display = "none"; arcgisRest.suggest(text, { authentication, params: { location: { x: -123.024, y: 49.274, spatialReference: { wkid: 4326 } }, maxSuggestions: 5 } }).then((response) => { suggestionsList.innerHTML = ""; if (!response.suggestions || response.suggestions.length === 0) { suggestionsList.style.display = "none"; return; } response.suggestions.forEach((s, idx) => { const li = document.createElement("li"); li.textContent = s.text; suggestionsList.appendChild(li); }); suggestionsList.style.display = "block"; }); });
Call the geocode
method
When the user selects a suggestion, call the geocode
method to get location coordinates.
-
Get the input field and initialize the popup.
Use dark colors for code blocks const input = document.getElementById("geocode-input"); let popup = null;
-
Use your access token to authenticate with ArcGIS REST JS and make requests to the geocoding service.
Use dark colors for code blocks const authentication = arcgisRest.ApiKeyManager.fromKey(accessToken);
-
Create a function that calls
geocode
using themagic
returned by theKey suggest
method. Themagic
helps match partial text input to a complete address. You will use this function in a later step.Key Use dark colors for code blocks function performGeocode(magicKey) { arcgisRest.geocode({ magicKey: magicKey, authentication }).then((response) => { const result = response.candidates[0]; if (!result) return; const lngLat = [result.location.x, result.location.y]; }); }
-
Add a click handler to each suggestion item to call the
perform
function with the suggestion'sGeocode magic
.Key Use dark colors for code blocks li.addEventListener("click", () => { input.value = s.text; suggestionsList.style.display = "none"; performGeocode(s.magicKey) });
Show the result
- Show the location details with a popup and pan the map to the location.
Use dark colors for code blocks function performGeocode(magicKey) { arcgisRest.geocode({ magicKey: magicKey, authentication }).then((response) => { const result = response.candidates[0]; if (!result) return; const lngLat = [result.location.x, result.location.y]; popup?.remove(); popup = new maplibregl.Popup() .setLngLat(lngLat) .setHTML(`<strong>${result.address}</strong><br />${lngLat[0].toFixed(4)}, ${lngLat[1].toFixed(4)}`) .addTo(map); map.flyTo({ center: lngLat }); }); }
Run the app
Run the app.
In the input box, type a partial address and see the suggestions come up. Click on a suggestion and the map will pan to the geocoded address and show a popup with the address details.What's next?
Learn how to use additional ArcGIS Location Services in these tutorials: