This is a simple example API to find the nearest store given an address or a zip code. The problem can be broken down in two parts, geocoding and spatial index.
The first step to solve the problem is to use a geocoding service to get the coordinates (latitude and longitude) of a given address or zip code.
There are multiple geocoding services available, probably the most famous is the Google Geocoding API, but for this project, I'm using the HERE Geocoder API.
The service will take the address or zip code as input and will return, among other things, the coordinates that we need for the next step.
The second step is to query a predefined dataset to find the nearest store to the coordinates obtained from the previous step. To do that efficiently, we need to build a spatial index, otherwise, we would have to scan to whole dataset every time.
As this is just a simple test, and we don't have a big dataset (less than 2000 stores), I'm loading the CSV file and building that index on memory, using the kdbush libray which creates the index based on a flat KD-tree.
To find the nearest store, I'm using the geokdbush library, a kdbush extension which provides a method to return the closest points from a given location, based on a kdbush index.
In a production environment with a large dataset, we would need a database to persist the stores. In this case, the idea is still the same, creating a spatial index, but that should be supported by the database. If using Postgres, for example, we could use PostGIS which is spatial database extender for PostgreSQL.
A live demo could be found here:
https://findstore-demo.herokuapp.com/closest
Parameter | Notes |
---|---|
address | Free-form text containing address elements. |
zip | Numeric zip code, e.g. 12345678. Dashes will be automatically stripped. |
units | Whether to display units in miles ("mi") or kilometers ("km"). Default: "mi". |
* address and zip cannot be used simultaneously, but one of them is required.
After cloning the project, first install the dependencies:
npm install
To run the project in your local machine, you're going to need a HERE account. Create an .env file inside of the src/config
directory, following the structure of the .env.example
file, using the APP ID and APP CODE that you can find on your HERE dashboard.
Then, simply start the project:
npm start
To run the tests, HERE credentials are not required. Just run:
npm test