Skip to content

Commit

Permalink
Merge 08cec04 into 3469541
Browse files Browse the repository at this point in the history
  • Loading branch information
tcql committed Nov 23, 2015
2 parents 3469541 + 08cec04 commit aa64a91
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
21 changes: 20 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

var rbush = require('rbush');
var lineclip = require('lineclip');

module.exports = whichPolygon;

Expand All @@ -22,13 +23,31 @@ function whichPolygon(data) {

var tree = rbush().load(bboxes);

return function query(p) {
function query(p) {
var result = tree.search([p[0], p[1], p[0], p[1]]);
for (var i = 0; i < result.length; i++) {
if (insidePolygon(result[i][4], p)) return result[i][5];
}
return null;
}

query.tree = tree;
query.bbox = function queryBbox(bbox) {
var result = tree.search(bbox).filter(function (el) {
// bbox is (possibly) completely inside the polygon. Keep it.
if (insidePolygon(el[4], [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2])) return true;
// polygon crosses or is totally inside the bbox. Keep it.
// Todo: account for holes.
if (lineclip(el[4][0], bbox).length > 0) return true;
return false;
}).map(function (el) {
return el[5];
});

return (result.length === 1) ? result[0] : result;
};

return query;
}

// ray casting algorithm for detecting if point is in polygon
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"description": "Index for matching points against a set of GeoJSON polygons",
"main": "index.js",
"dependencies": {
"lineclip": "^1.1.5",
"rbush": "^1.4.1"
},
"devDependencies": {
Expand Down
13 changes: 12 additions & 1 deletion test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,20 @@ var data = require('./fixtures/states.json');

var query = whichPolygon(data);

test('queries polygons', function (t) {
test('queries polygons with a point', function (t) {
t.equal(query([-100, 45]).name, "South Dakota");
t.equal(query([-90, 30]).name, "Louisiana");
t.equal(query([-50, 30]), null);
t.end();
});


test('queries polygons with a bbox', function (t) {
t.equal(query.bbox([-100, 45, -99.5, 45.5]).name, "South Dakota");

var qq = query.bbox([-104.2, 44, -103, 45]);
var names = qq.map(function (el) { return el.name; }).sort();
t.equal(qq.length, 2);
t.like(names, ["South Dakota", "Wyoming"]);
t.end();
});

0 comments on commit aa64a91

Please sign in to comment.