covutils
Version:
Utilities for creating, transforming, and handling Coverage Data objects.
58 lines (48 loc) • 2.06 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ensureClockwisePolygon = ensureClockwisePolygon;
exports.getPointInPolygonsFn = getPointInPolygonsFn;
var _pointInBigPolygon = require('point-in-big-polygon');
var _pointInBigPolygon2 = _interopRequireDefault(_pointInBigPolygon);
var _spherical = require('topojson/lib/topojson/spherical.js');
var _cartesian = require('topojson/lib/topojson/cartesian.js');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Modifies the point order of the given polygon rings such that the first ring is ordered
* clockwise and all others anti-clockwise. Modification happens in-place.
*
* @param {Array} rings - Polygon rings to reorder (in-place)
* @param {boolean} [isCartesian=false] - whether coordinates are cartesian or spherical degrees
*/
function ensureClockwisePolygon(rings) {
var isCartesian = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
// first ring = exterior, clockwise
// other rings = interior, anti-clockwise
var ringAreaFn = isCartesian ? _cartesian.ringArea : _spherical.ringArea;
for (var i = 0; i < rings.length; i++) {
var area = ringAreaFn(rings[i]);
if (i === 0 && area < 0 || i > 0 && area > 0) {
rings[i].reverse();
}
}
}
/**
* Preprocesses an array of polygons to answer the point-in-polygon question efficiently.
*
* @param {Array} polygons - A list of polygons where the exterior ring of each polygon is in clockwise and the interior rings in anti-clockwise order.
* @return {function} A function classify(point) which returns the index of the first found polygon containing point, or -1 if not in any polygon.
*/
function getPointInPolygonsFn(polygons) {
var classifiers = polygons.map(_pointInBigPolygon2.default);
var npolys = polygons.length;
return function (point) {
for (var i = 0; i < npolys; i++) {
if (classifiers[i](point) <= 0) {
return i;
}
}
return -1;
};
}