전제

Turf.js는 GeoJSON Feature를 입력으로 받습니다. 좌표계는 보통 WGS84(경도, 위도) 기준이며, 링은 닫혀 있어야 합니다.

설치

npm install @turf/helpers @turf/union @turf/difference @turf/intersect @turf/area

샘플 데이터

import { polygon, featureCollection } from '@turf/helpers';
 
const a = polygon([[
  [0, 0], [2, 0], [2, 2], [0, 2], [0, 0],
]]);
 
const b = polygon([[
  [1, 1], [3, 1], [3, 3], [1, 3], [1, 1],
]]);

1) 합집합 union

import { union } from '@turf/union';
 
const merged = union(featureCollection([a, b]));
  • 겹치지 않는 경우 결과가 MultiPolygon일 수 있습니다.
  • 입력이 많으면 먼저 단순화 후 연산하는 편이 안정적입니다.

2) 차집합 difference

import { difference } from '@turf/difference';
 
const onlyA = difference(featureCollection([a, b]));
  • b가 a를 완전히 덮으면 결과는 null입니다.

3) 교집합 intersect

import { intersect } from '@turf/intersect';
 
const overlap = intersect(featureCollection([a, b]));
if (!overlap) {
  console.log('겹치는 영역 없음');
}

결과 검증

import area from '@turf/area';
 
if (overlap) {
  console.log(area(overlap));
}
  • 공간 연산 결과는 반드시 면적/좌표 검증을 같이 두는 것이 안전합니다.

실무 팁

  • 폴리곤이 매우 복잡하면 연산 전 단순화(simplify) 적용.
  • 자기 교차(self-intersection) 폴리곤은 먼저 정리.
  • 클라이언트 연산이 무거우면 서버(PostGIS)로 오프로드.

요약

Turf 연산 자체는 간단하지만, 실패의 대부분은 입력 품질 문제입니다. null 처리, 좌표 유효성, 후처리 검증 세 가지를 기본 규칙으로 두면 안정적으로 운영할 수 있습니다.