polygon.js 2.2 KB

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