Learn how to find an address near a location with the geocoding service.
Reverse geocode coordinates to addresses with the geocoding service.
Reverse geocoding is the process of converting a location to an address or place. To reverse geocode, you use the Geocoding service and the reverseGeocode 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 reverseGeocode method of ArcGIS REST JS to reverse geocode and find the closest address to your clicked location on the map.
To access location services, you need an API key or OAuth 2.0 access token. To learn how to create and scope your key, visit the Create an API key tutorial.
Go to your dashboard to get an API key. The API key must be scoped to access the services used in this tutorial.
In CodePen, update apiKey to use your key.
Use dark colors for code blocks
Change line
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const apiKey = "YOUR_API_KEY";
const basemapEnum = "arcgis/streets";
const map = new maplibregl.Map({
container: "map", // the id of the div elementstyle: `https://basemapstyles-api.arcgis.com/arcgis/rest/services/styles/v2/styles/${basemapEnum}?token=${apiKey}`,
zoom: 12, // starting zoomcenter: [-118.805, 34.027] // starting location [longitude, latitude]});
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.
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 lngLat.
The lngLat property is a LngLat. It has lng and lat properties and a toArray 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 the lngLat property of the event parameter.
Use the ArcGIS REST JS reverseGeocode method to find an address closest to a point.
Inside the click handler, create a new arcgisRest.ApiKeyManager to access the geocoding service. Call the arcgisRest.reverseGeocode method with the coordinates array.
The response from the reverseGeocode 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].
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.