How to Find Address Coordinates using Node.js
Tags: node, webdev, opensource, api
Published: 2022-10-12 14:49:09

**_Highlighting ArcGIS REST JS_**

Many developers know just how powerful Node.js can be for building applications. And, many developers are keen on using open-source APIs for their applications. So, what if a lightweight, [open-source](https://github.com/Esri/arcgis-rest-js) option to find the latitude and longitude of an address in just a few lines of code using Node.js exists? Well, it does! In fact, both ways are possible (coordinates to address/location and address/location to coordinates). Let’s dive into it!

```javascript
geocode({
  address: "1600 Pennsylvania Ave",
  countryCode: "USA"
}).then((res) => {
  console.log(res);
});
```

## Video & Tutorial
This article is inspired by the Search for an Address [tutorial](https://developers.arcgis.com/arcgis-rest-js/) on the ArcGIS REST JS documentation page along with the video below. You can also find the complete code solution in [this repo](https://github.com/cyatteau/ArcGIS-REST-JS-search-address).

{% embed https://youtu.be/qJf0kkZoPqc %}

## What is ArcGIS REST JS?
_So exactly what is ArcGIS REST JS?_ As mentioned above, it is a convenient and lightweight collection of modules that can be used for binding to the [ArcGIS services](https://developers.arcgis.com/rest/) REST APIs. The modules are meant for developers who wish to work directly with the services using JavaScript or TypeScript. Note: For those of you using Python, the [ArcGIS API for Python](https://developers.arcgis.com/python/guide/part2-locating-addresses/) offers similar functionality.

## Getting Started
Before diving into the steps for finding location coordinates, let’s start with a few prerequisites. There are two things we’ll need to do before jumping into the code. These are:

1. Sign up for a free [ArcGIS Developer Account](https://developers.arcgis.com/sign-up) (no credit card required).
2. Create a personal [API Key](https://youtu.be/StVncn6DLzc).

Upon completing the two items above, we’ll now have access to several location services including basemap layers, geocoding, routing, and much [more](https://developers.arcgis.com/documentation/mapping-apis-and-services/services/).

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4mhq5romt836drtfj3hp.png)

## Setting Up
We’ll be using Visual Studio Code to run our Node.js application. To start, we’ll need to set up a Node.js project. Next, to access location services, we’re going to need to access two ArcGIS REST packages. The first is the [request package](https://developers.arcgis.com/arcgis-rest-js/api-reference/arcgis-rest-request/). This contains the authentication helper that we’ll utilize to validate our requests. The second is the [geocoding package](https://developers.arcgis.com/arcgis-rest-js/api-reference/arcgis-rest-geocoding/). This is a wrapper used to access different geocoding tools like reverse geocode, suggest, and geocode. To install each of these packages, we’ll use npm with the following commands:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9lsuw6jbgw7lzk9jc3dw.png)

Now that we have installed the necessary dependencies, we’ll be able to use each of these through named imports, specifying only the exports needed from the ES modules. With that, let’s get into the code!

## Steps for Creating the Script File
Now that we’re done setting everything up, we’ll need to place all of our code inside a script file.

**Step 1:** The first thing we’ll do is bring in those named imports mentioned above. These are:

```javascript
import { ApiKeyManager } from '@esri/arcgis-rest-request;
import { geocode } from '@esri/arcgis-rest-geocoding;
```

**Step 2:** Next, we’ll need to scope our API key. Remember, this can be found in the [ArcGIS developer dashboard](https://developers.arcgis.com/dashboard/).

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tp88o7dt5mk4ppd16l23.png)

**Step 3:** We’ll also define an authentication parameter that will be needed for the request using the ApiKeyManager import. For security purposes, API keys should be kept secure and should not be committed to a repo. It is recommended to use an environment variable or external config file (ignored in .gitignore) for the API key.

```javascript
const apiKey = "PERSONAL_API_KEY";
const authentication = ApiKeyManager.fromKey(apiKey);
```
**Step 4:** We’ll now make a call to the geocoding service by using the geocode import. This service requires a few parameters to be properly utilized. To ensure accurate results, we’ll use the `address`, `postal`, `countryCode`, and `authentication` parameters, as shown below.

```javascript
geocode({
  address: "street address",
  postal: value,
  countryCode: "country",
  authentication
})
```

**Step 5:** Finally, before running this application we’ll handle getting the results by logging our results to the console. After doing so, our entire script file should look like the image below.

```javascript
import { ApiKeyManager } from '@esri/arcgis-rest-request;
import { geocode } from '@esri/arcgis-rest-geocoding;
const apiKey = "PERSONAL_API_KEY";
const authentication = ApiKeyManager.fromKey(apiKey);
geocode({
  address: "street address",
  postal: value,
  countryCode: "country",
  authentication
}).then((res) => {
  console.log(res.candidates);
});
```

## Execution and Results
We’re ready to execute the application. Remember, the expectation here is that the address we passed to the geocoding service will result in location coordinates. We’ll run the application using the proper `node` command in the terminal window. After doing so the results should resemble the image below (but will vary dependent upon the parameter values passed in).

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/691o24ovxf6i2nxgzwb2.png)

And just like that, we get the longitude (`y`) and latitude (`x`) of the location we passed to the geocoding service. Along with the location coordinates, there are many other values returned.

## Score
Out of the results, the score is quite helpful for geocoding purposes. Notice the score for the first result is 100, while the score for the second result is 98.3. The first result matches the parameters passed in exactly, which is why the perfect score of 100 is returned. On the other hand, the second result is a close match but has a different postal code, hence the lower score of 98.3. While significant, it is essential to note that the score value is not absolute and should be used for verification purposes over justification.

## Extent & Spatial Reference
The `extent` result describes a set of bounding box coordinates that show the search area of the result(s). This [value](https://developers.arcgis.com/rest/geocode/api-reference/geocoding-find-address-candidates.htm#ESRI_SECTION1_E7214BD3ADA34C50A2B88C08F253DF41) can be used to confine a specified area when searching for locations, called as `searchExtent`. No candidates outside of the specified area will be returned. The `searchExtent` parameter can be used with all supported search types.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4p2o9d34q04llpnxl2mv.png)

The `spatialReference` value defines the coordinate system used to locate the geometry for a feature. It is used to accurately display features and perform spatial analysis. By default, the spatial reference is set to WKID=4326. The value of 4326 indicates the response is in GPS coordinates (latitude and longitude), formally known as [WGS 84](https://medium.com/r/?url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FWorld_Geodetic_System). ArcGIS allows you to use thousands of different spatial references and offers many tools for working with [spatial references](https://developers.arcgis.com/documentation/spatial-references/).

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v3nnfmx19wru3htg4r4v.png)

## What makes ArcGIS geocoding special?
With the free developer account, access to up to 20,000 geocode requests per month is granted for free, which is more than enough for personal and small-scale applications. For larger projects, the pricing is extremely affordable. The ArcGIS geocoding service pricing is very competitive and beats out competitors at many price points. Esri also allows the [storing of geocoding](https://developers.arcgis.com/documentation/mapping-apis-and-services/search/services/geocoding-service/#storage-parameter) results, which is something not all geocoding providers certainly can’t say they offer!

Esri allows developers to build other services/APIs on top of ArcGIS location services and resell it. Developers also are not restricted to where results can be displayed. For example, you can display your results with Leaflet, MapLibre, OpenLayers, etc. Additionally, developers can rest assured that there is no tracking/telemetry of the data that is sent to ArcGIS services. Esri respects 100% of customers' privacy and ownership.

## Conclusion
This small application created above displays how powerful ArcGIS REST JS can be in such a compact form factor. As shown throughout this article, the ease of use, minimal size footprint, and accessibility make ArcGIS REST JS a go-to library for performing geocoding operations. It should be noted that there is much more that can be done through the modules used here along with other ArcGIS REST JS modules, including [routing](https://developers.arcgis.com/arcgis-rest-js/route-and-directions/find-a-route-and-directions/), [data queries](https://developers.arcgis.com/arcgis-rest-js/layers/query-a-feature-layer-sql/), and [demographic queries](https://developers.arcgis.com/arcgis-rest-js/demographic-data/query-demographic-data/).

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qzed66f42b3417okiu17.png)

In conclusion, ArcGIS REST JS is a prime option for creating applications where location services are needed.

_This article was written by Courtney Yatteau, a Developer Advocate at [Esri](https://www.esri.com/en-us/home). The opinions in this article are solely Courtney’s opinions and do not necessarily represent the postings, strategies, or opinions of her employer. If you have any feedback, please like and/or comment. Also, if you have any questions or comments that you’d prefer to send privately, you can contact Courtney through [Twitter](https://twitter.com/c_yatteau) or [email](http://DeveloperOutreach@esri.com/)._

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/62lcy19fzckojl1h9jel.png)