Learn how to find an address near a location.
Reverse geocoding is the process of converting a location to an address or place. To reverse geocode, you use the Geocoding service and the reverse
operation. This operation requires an initial location and returns an address with attributes such as place name and location.
In this tutorial, you use the reverse
method of ArcGIS REST JS to reverse geocode and find the closest address to your clicked location on the map.
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
This tutorial uses ArcGIS REST JS for reverse geocoding.
-
In the
<head
element, add references to the ArcGIS REST JS library.> Use dark colors for code blocks <head> <meta charset="utf-8" /> <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" /> <script src=https://unpkg.com/maplibre-gl@4/dist/maplibre-gl.js></script> <link href=https://unpkg.com/maplibre-gl@4/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 the map initialization to center on location
[2.3522,48.8566]
, Paris.Use dark colors for code blocks <script> /* Use for API key authentication */ const accessToken = "YOUR_ACCESS_TOKEN"; // or /* Use for user authentication */ // const session = await arcgisRest.ArcGISIdentityManager.beginOAuth2({ // clientId: "YOUR_CLIENT_ID", // Your client ID from OAuth credentials // redirectUri: "YOUR_REDIRECT_URL", // The redirect URL registered in your OAuth credentials // portal: "YOUR_PORTAL_URL" // Your portal URL // }) // const accessToken = session.token; 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: 12, center: [2.3522, 48.8566] // Paris }); map._controls[0].options.customAttribution += " | Powered by Esri " map._controls[0]._updateAttributions() </script>
Add a click event handler
Before you call the Geocoding service, you need to get a location from the user. You can add a handler to the Map
's click
event. The click handler will be called with an object containing parameters such as lng
.
The lng
property is a Lng
. It has lng
and lat
properties and a to
method which returns an array in [longitude, latitude] order.
-
After the map initialization code, add a handler for the
click
event. Create a coordinates array from thelng
property of the event parameter.Lat Use dark colors for code blocks <script> /* Use for API key authentication */ const accessToken = "YOUR_ACCESS_TOKEN"; // or /* Use for user authentication */ // const session = await arcgisRest.ArcGISIdentityManager.beginOAuth2({ // clientId: "YOUR_CLIENT_ID", // Your client ID from OAuth credentials // redirectUri: "YOUR_REDIRECT_URL", // The redirect URL registered in your OAuth credentials // portal: "YOUR_PORTAL_URL" // Your portal URL // }) // const accessToken = session.token; 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: 12, center: [2.3522, 48.8566] // Paris }); map.on("click", (e) => { const coords = e.lngLat.toArray(); }); map._controls[0].options.customAttribution += " | Powered by Esri " map._controls[0]._updateAttributions() </script>
Call the service
Use the ArcGIS REST JS reverse
method to find an address closest to a point.
-
Inside the click handler, create a new
arcgis
to access the geocoding service. Call theRest. Api Key Manager arcgis
method with the coordinates array.Rest.reverse Geocode Use dark colors for code blocks map.on("click", (e) => { const coords = e.lngLat.toArray(); const authentication = arcgisRest.ApiKeyManager.fromKey(accessToken); arcgisRest .reverseGeocode(coords, { authentication }) .then((result) => { });
Display the result
The response from the reverse
operation contains two properties. address
is a structured object with fields such as street name and business name. location
contains the location of the returned address, which may differ from the coordinates you provided.
Use the results to display a pop-up with the address
and location
values.
-
Convert the
result.location
object into an array of[longitude, latitude]
.Use dark colors for code blocks arcgisRest .reverseGeocode(coords, { authentication }) .then((result) => { const lngLat = [result.location.x, result.location.y];
-
Set a variable containing the text you want to display, using the address and coordinates.
Use dark colors for code blocks const lngLat = [result.location.x, result.location.y]; const label = `${result.address.LongLabel}<br>${lngLat[0].toLocaleString()}, ${lngLat[1].toLocaleString()}`; })
-
Add a pop-up to display the label at the returned coordinates.
To add a pop-up to the map, you use the
Popup
class in MapLibre GL JS. See the Display a pop-up tutorial for more information.Use dark colors for code blocks const lngLat = [result.location.x, result.location.y]; const label = `${result.address.LongLabel}<br>${lngLat[0].toLocaleString()}, ${lngLat[1].toLocaleString()}`; new maplibregl.Popup().setLngLat(lngLat).setHTML(label).addTo(map); })
Handle errors
To handle errors that occur when accessing the Geocoding service, such as networking or API key issues, use an error handler to show a message to the user.
-
Add a handler to catch any exception and display a message to the user.
Use dark colors for code blocks const authentication = arcgisRest.ApiKeyManager.fromKey(accessToken); arcgisRest .reverseGeocode(coords, { authentication }) .then((result) => { const lngLat = [result.location.x, result.location.y]; const label = `${result.address.LongLabel}<br>${lngLat[0].toLocaleString()}, ${lngLat[1].toLocaleString()}`; new maplibregl.Popup().setLngLat(lngLat).setHTML(label).addTo(map); }) .catch((error) => { alert("There was a problem using the reverse geocode service. See the console for details."); console.error(error); });
Run the app
Run the app.
Click on the map to reverse geocode the clicked point and display a pop-up with the closest address and coordinates.
What's next?
Learn how to use additional ArcGIS location services in these tutorials: