primary-area.mjs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import * as turf from '@turf/turf'
  2. export const PRIMARY_AREA_BOUNDS = Object.freeze([
  3. 110.328749941417,
  4. 28.3917230659234,
  5. 110.465779226663,
  6. 28.4913038992907,
  7. ])
  8. const primaryArea = turf.bboxPolygon(PRIMARY_AREA_BOUNDS)
  9. export function isWithinPrimaryArea(feature, bounds = PRIMARY_AREA_BOUNDS) {
  10. return turf.booleanWithin(feature, turf.bboxPolygon(bounds))
  11. }
  12. export function clipFeatureToBounds(feature, bounds = PRIMARY_AREA_BOUNDS) {
  13. const type = feature.geometry?.type
  14. let clipped
  15. if (type === 'LineString' || type === 'MultiLineString') {
  16. clipped = turf.bboxClip(feature, bounds)
  17. } else if (type === 'Polygon' || type === 'MultiPolygon') {
  18. clipped = turf.intersect(turf.featureCollection([feature, turf.bboxPolygon(bounds)]))
  19. } else {
  20. clipped = turf.booleanWithin(feature, primaryArea) ? feature : null
  21. }
  22. if (!clipped) return null
  23. const coordinates = clipped.geometry?.coordinates
  24. if (Array.isArray(coordinates) && coordinates.length === 0) return null
  25. if (Array.isArray(coordinates) && coordinates.every((part) => Array.isArray(part) && part.length === 0)) return null
  26. if (turf.area(clipped) === 0 && type !== 'LineString' && type !== 'MultiLineString') return null
  27. return { ...clipped, properties: { ...feature.properties } }
  28. }
  29. export function isInsidePrimaryArea(point) {
  30. return point.length === 2 &&
  31. Number.isFinite(point[0]) &&
  32. Number.isFinite(point[1]) &&
  33. point[0] >= PRIMARY_AREA_BOUNDS[0] &&
  34. point[0] <= PRIMARY_AREA_BOUNDS[2] &&
  35. point[1] >= PRIMARY_AREA_BOUNDS[1] &&
  36. point[1] <= PRIMARY_AREA_BOUNDS[3]
  37. }