UNPKG

2.06 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.ensureClockwisePolygon = ensureClockwisePolygon;
7exports.getPointInPolygonsFn = getPointInPolygonsFn;
8
9var _pointInBigPolygon = require('point-in-big-polygon');
10
11var _pointInBigPolygon2 = _interopRequireDefault(_pointInBigPolygon);
12
13var _spherical = require('topojson/lib/topojson/spherical.js');
14
15var _cartesian = require('topojson/lib/topojson/cartesian.js');
16
17function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18
19/**
20 * Modifies the point order of the given polygon rings such that the first ring is ordered
21 * clockwise and all others anti-clockwise. Modification happens in-place.
22 *
23 * @param {Array} rings - Polygon rings to reorder (in-place)
24 * @param {boolean} [isCartesian=false] - whether coordinates are cartesian or spherical degrees
25 */
26function ensureClockwisePolygon(rings) {
27 var isCartesian = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
28
29 // first ring = exterior, clockwise
30 // other rings = interior, anti-clockwise
31 var ringAreaFn = isCartesian ? _cartesian.ringArea : _spherical.ringArea;
32 for (var i = 0; i < rings.length; i++) {
33 var area = ringAreaFn(rings[i]);
34 if (i === 0 && area < 0 || i > 0 && area > 0) {
35 rings[i].reverse();
36 }
37 }
38}
39
40/**
41 * Preprocesses an array of polygons to answer the point-in-polygon question efficiently.
42 *
43 * @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.
44 * @return {function} A function classify(point) which returns the index of the first found polygon containing point, or -1 if not in any polygon.
45 */
46function getPointInPolygonsFn(polygons) {
47 var classifiers = polygons.map(_pointInBigPolygon2.default);
48 var npolys = polygons.length;
49
50 return function (point) {
51 for (var i = 0; i < npolys; i++) {
52 if (classifiers[i](point) <= 0) {
53 return i;
54 }
55 }
56 return -1;
57 };
58}
\No newline at end of file