lineString.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { SYMBOL_GEO_LINE_STRING } from '../helper/symbol';
  2. import { Point } from './point';
  3. import { isArray, isNumber } from '../utils/type';
  4. export class LineString {
  5. constructor(points) {
  6. if (!isArray(points)) {
  7. throw new TypeError(`"points" must be of type Point[]. Received type ${typeof points}`);
  8. }
  9. if (points.length < 2) {
  10. throw new Error('"points" must contain 2 points at least');
  11. }
  12. points.forEach(point => {
  13. if (!(point instanceof Point)) {
  14. throw new TypeError(`"points" must be of type Point[]. Received type ${typeof point}[]`);
  15. }
  16. });
  17. this.points = points;
  18. }
  19. parse(key) {
  20. return {
  21. [key]: {
  22. type: 'LineString',
  23. coordinates: this.points.map(point => point.toJSON().coordinates)
  24. }
  25. };
  26. }
  27. toJSON() {
  28. return {
  29. type: 'LineString',
  30. coordinates: this.points.map(point => point.toJSON().coordinates)
  31. };
  32. }
  33. static validate(lineString) {
  34. if (lineString.type !== 'LineString' || !isArray(lineString.coordinates)) {
  35. return false;
  36. }
  37. for (let point of lineString.coordinates) {
  38. if (!isNumber(point[0]) || !isNumber(point[1])) {
  39. return false;
  40. }
  41. }
  42. return true;
  43. }
  44. static isClosed(lineString) {
  45. const firstPoint = lineString.points[0];
  46. const lastPoint = lineString.points[lineString.points.length - 1];
  47. if (firstPoint.latitude === lastPoint.latitude && firstPoint.longitude === lastPoint.longitude) {
  48. return true;
  49. }
  50. }
  51. get _internalType() {
  52. return SYMBOL_GEO_LINE_STRING;
  53. }
  54. }