Skip to content

Commit

Permalink
switch from kdtree library to kdt because it will work with browserify
Browse files Browse the repository at this point in the history
  • Loading branch information
Nick Carneiro committed Nov 28, 2014
1 parent 3cdc711 commit 241ddfb
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 13 deletions.
23 changes: 11 additions & 12 deletions index.js
@@ -1,7 +1,7 @@
//load zip csv into memory into a format we can easily iterate over
//executed when gps2zip is required
var fs = require('fs');
var kd = require('kdtree');
var kdt = require('kdt');
var zips = [];
try {
// zip code data is sorted by ascending latitude
Expand All @@ -10,20 +10,19 @@ try {

//zips is a global defined up top
zips = JSON.parse(data);

var tree = new kd.KDTree(2);
for (var i = 0; i < zips.length; i++){
tree.insert(zips[i].latitude, zips[i].longitude, i);
}
var distance = function(a, b){
return Math.pow(a.latitude - b.latitude, 2) + Math.pow(a.longitude - b.longitude, 2);
};
var tree = kdt.createKdTree(zips, distance, ['latitude', 'longitude']);
} catch (err) {
console.error("There was an error opening the zip code file:");
console.log(err);
}

exports.gps2zip = function(lat, lon){

var result = tree.nearest(lat, lon);
var nearestIndex = result[2];
return zips[nearestIndex];

exports.gps2zip = function(latitude, longitude){
// we've already constructed the kd-tree. Just find the nearest location
var results = tree.nearest({'latitude': latitude, 'longitude': longitude}, 1);
var firstResult = results[0];
var zipCode = firstResult[0];
return zipCode;
};
2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -5,7 +5,7 @@
"author": "Nick Carneiro <nickc@trillworks.com>",
"dependencies": {
"tape": ">= 3.0.3",
"kdtree": "0.0.10"
"kdt": "0.1.0"
},
"main": "index.js",
"keywords": ["zip code", "zip", "geolocation", "location"],
Expand Down

0 comments on commit 241ddfb

Please sign in to comment.