polygon.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const symbol_1 = require("../helper/symbol");
  4. const type_1 = require("../utils/type");
  5. const lineString_1 = require("./lineString");
  6. class Polygon {
  7. constructor(lines) {
  8. if (!type_1.isArray(lines)) {
  9. throw new TypeError(`"lines" must be of type LineString[]. Received type ${typeof lines}`);
  10. }
  11. if (lines.length === 0) {
  12. throw new Error('Polygon must contain 1 linestring at least');
  13. }
  14. lines.forEach(line => {
  15. if (!(line instanceof lineString_1.LineString)) {
  16. throw new TypeError(`"lines" must be of type LineString[]. Received type ${typeof line}[]`);
  17. }
  18. if (!lineString_1.LineString.isClosed(line)) {
  19. throw new Error(`LineString ${line.points.map(p => p.toReadableString())} is not a closed cycle`);
  20. }
  21. });
  22. this.lines = lines;
  23. }
  24. parse(key) {
  25. return {
  26. [key]: {
  27. type: 'Polygon',
  28. coordinates: this.lines.map(line => {
  29. return line.points.map(point => [point.longitude, point.latitude]);
  30. })
  31. }
  32. };
  33. }
  34. toJSON() {
  35. return {
  36. type: 'Polygon',
  37. coordinates: this.lines.map(line => {
  38. return line.points.map(point => [point.longitude, point.latitude]);
  39. })
  40. };
  41. }
  42. static validate(polygon) {
  43. if (polygon.type !== 'Polygon' || !type_1.isArray(polygon.coordinates)) {
  44. return false;
  45. }
  46. for (let line of polygon.coordinates) {
  47. if (!this.isCloseLineString(line)) {
  48. return false;
  49. }
  50. for (let point of line) {
  51. if (!type_1.isNumber(point[0]) || !type_1.isNumber(point[1])) {
  52. return false;
  53. }
  54. }
  55. }
  56. return true;
  57. }
  58. static isCloseLineString(lineString) {
  59. const firstPoint = lineString[0];
  60. const lastPoint = lineString[lineString.length - 1];
  61. if (firstPoint[0] !== lastPoint[0] || firstPoint[1] !== lastPoint[1]) {
  62. return false;
  63. }
  64. return true;
  65. }
  66. get _internalType() {
  67. return symbol_1.SYMBOL_GEO_POLYGON;
  68. }
  69. }
  70. exports.Polygon = Polygon;