Skip to content

Commit

Permalink
✨ add limit option to main function
Browse files Browse the repository at this point in the history
Can now request first `n` ZIP codes instead of just one result.

Resolves #8
  • Loading branch information
blakek committed Mar 22, 2019
1 parent d359202 commit 3873dce
Show file tree
Hide file tree
Showing 3 changed files with 131 additions and 32 deletions.
99 changes: 84 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,41 +1,110 @@
# geo2zip [![Travis](https://img.shields.io/travis/blakek/geo2zip/master.svg)](https://travis-ci.org/blakek/geo2zip)
# geo2zip

> Translates latitude / longitude geolocations to the nearest corresponding U.S. zip code
> 🌎🔍 Quickly find the the nearest U.S. ZIP codes to a latitude/longitude geolocation using k-nearest neighbors
Takes a geolocation and returns the nearest US ZIP code.
[![Travis](https://img.shields.io/travis/blakek/geo2zip/master.svg)][1]

⚠️ **NOTE:** this may not return the actual ZIP code of the location; it returns the ZIP code where the approximate center of the ZIP is nearest the location.
Takes a geolocation and returns the nearest US ZIP codes.

⚠️ **NOTE:** The top result may not return the _actual_ ZIP code containing the
location. This library returns the ZIP code where the approximate center of the
ZIP is nearest the given location. Larger ZIP code areas may show lower in the
results when searching nearby points because the center can be so far away. If
you're relying on something as inaccurate as ZIP codes, the top result is likely
close enough.

Also, ZIP codes change. They change in shape and location. New ones are
created and old ones are removed. They're even recycled. If you know of a
reliable, more up-to-date list of ZIP codes, please let us know by opening an
issue.

**Can I use this in the browser?** Yes but please don't. This is made to run on
a Node.js server. This depends on a roughly [2 MB list of US ZIP
codes][2] and sorts those in-memory. Please
don't do that to my phone. If you're experimenting or know what you're doing,
use this wherever and however it works for you.

**Isn't sorting and filtering on a 2MB file slow in JavaScript?** No. A lookup
is created when the main file is imported/required. After the lookup is created,
you should be able to run the examples in this README millions of times per
second; showing output would be the limit. The tradeoff is your server may take
a 1-2 seconds longer to start up initially (e.g. from `npm run start`).

## Install

With [Yarn](https://yarnpkg.com/en/) or [npm](https://npmjs.org/) installed,
run:

```shell
yarn add geo2zip

# ...or, if using `npm`
npm install geo2zip
```

## Usage

Get the nearest ZIP to a location:

```js
const geo2zip = require('geo2zip')
import geo2zip from 'geo2zip'

const somewhere = {
const location = {
latitude: 34.659698,
longitude: -88.242903
}

geo2zip(somewhere).then(zip => {
console.log(zip) // '38873'
})
const closestZip = await geo2zip(location)

console.log(closestZip) // ['38873']
```

## Install
Get the closest 5 ZIPs to a location:

With [npm](https://npmjs.org/) installed, run
```js
import geo2zip from 'geo2zip'

const location = {
latitude: 34.659698,
longitude: -88.242903
}

await geo2zip(location, { limit: 5 })
// [ '38873', '38838', '38827', '38859', '38852' ]
```
$ npm install geo2zip
```

## API

### `geo2zip(location, options)`

#### location

Type: `Object`

A geolocation with valid `latitude` and `longitude` properties.

#### options

Type: `Object`

Properties:

- `limit` - the number of results to return
- Type: `Number`
- Default: `1`

## See Also

* [`blakek/standardize-geolocation`](https://github.com/blakek/standardize-geolocation) - takes geolocations of different formats and outputs a standardized version
* [`blakek/us-zips`](https://github.com/blakek/us-zips) - a list of US ZIP codes and their geolocations
- [`standardize-geolocation`][3] - takes geolocations of different formats and
outputs a standardized version
- [`sphere-knn`][4] - find the k nearest neighbors for points on a sphere
- [`us-zips`][2] - a list of US ZIP codes and their geolocations

## License

MIT

[1]: https://travis-ci.org/blakek/geo2zip
[2]: https://github.com/blakek/us-zips
[3]: https://github.com/blakek/standardize-geolocation
[4]: https://github.com/darkskyapp/sphere-knn
18 changes: 15 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,23 @@ const sphereKnn = require('sphere-knn')
const { standardizeGeolocation } = require('standardize-geolocation')
const usZips = require('us-zips/array')

// Start building lookup when module imported
const lookup = sphereKnn(usZips)

function geo2zip (rawLocation) {
const { latitude, longitude } = standardizeGeolocation(rawLocation)
return Promise.resolve(lookup(latitude, longitude, 1)[0].zipCode)
// Retain most-used behavior
const defaultOptions = { limit: 1 }

// Don't recreate this function on every run
const pluckZipCode = obj => obj.zipCode

function geo2zip (location, extraOptions) {
return new Promise(resolve => {
const options = { ...defaultOptions, ...extraOptions }
const { latitude, longitude } = standardizeGeolocation(location)
const results = lookup(latitude, longitude, options.limit)

resolve(results.map(pluckZipCode))
})
}

module.exports = geo2zip
46 changes: 32 additions & 14 deletions test.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,42 @@
import test from 'ava'
import geo2zip from '.'

test('returns zip code from same geolocation', async t => {
const exactly38873 = {
latitude: 34.659698,
longitude: -88.242903
}
test('returns zip code nearest a geolocation', async t => {
const testPoints = [
{
expected: '38873',
location: { latitude: 34.659698, longitude: -88.242903 }
},
{
expected: '37076',
location: { latitude: 36.142226, longitude: -86.618779 }
}
]

const zip = await geo2zip(exactly38873)
const tests = testPoints.map(async ({ expected, location }) => {
const actual = await geo2zip(location)
t.is(actual[0], expected)
})

t.is(zip, '38873')
return Promise.all(tests)
})

test('returns nearest zip code for geolocation', async t => {
const near37076 = {
latitude: 36.142226,
longitude: -86.618779
}
test('returns a list of zip codes nearest a location, ordered by closeness', async t => {
const testPoints = [
{
expected: '38859',
location: { latitude: 34.659698, longitude: -88.242903 }
},
{
expected: '37214',
location: { latitude: 36.1432503, longitude: -86.6202267 }
}
]

const zip = await geo2zip(near37076)
const tests = testPoints.map(async ({ expected, location }) => {
const actual = await geo2zip(location, { limit: 5 })
t.true(actual.includes(expected))
})

t.is(zip, '37076')
return Promise.all(tests)
})

0 comments on commit 3873dce

Please sign in to comment.