From 5089e2370b3f0ece7bf80ca4d548e0e5898c6e2c Mon Sep 17 00:00:00 2001 From: John Firebaugh Date: Sun, 13 Jan 2013 17:11:43 -0800 Subject: [PATCH] Point-in-polygon algorithm No tests. I didn't write it so I assume it's correct! --- js/id/util.js | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/js/id/util.js b/js/id/util.js index 91bbbb1c1..20cb722dc 100644 --- a/js/id/util.js +++ b/js/id/util.js @@ -107,3 +107,29 @@ iD.util.geo.chooseIndex = function(way, point, map) { loc: loc }; }; + +// Return whether point is contained in polygon. +// +// `point` should be a 2-item array of coordinates. +// `polygon` should be an array of 2-item arrays of coordinates. +// +// From https://github.com/substack/point-in-polygon. +// ray-casting algorithm based on +// http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html +// +iD.util.geo.pointInPolygon = function(point, polygon) { + var x = point[0], + y = point[1], + inside = false; + + for (var i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { + var xi = polygon[i][0], yi = polygon[i][1]; + var xj = polygon[j][0], yj = polygon[j][1]; + + var intersect = ((yi > y) != (yj > y)) + && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); + if (intersect) inside = !inside; + } + + return inside; +};