-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
82 lines (80 loc) · 2.45 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// depend on jsts for now https://github.com/bjornharrtell/jsts/blob/master/examples/overlay.html
var jsts = require('jsts');
/**
* Takes two {@link Polygon|polygons} and finds their intersection. If they share a border, returns the border; if they don't intersect, returns undefined.
*
* @module turf/intersect
* @category transformation
* @param {Feature<Polygon>} poly1 the first polygon
* @param {Feature<Polygon>} poly2 the second polygon
* @return {(Feature<Polygon>|undefined|Feature<MultiLineString>)} if `poly1` and `poly2` overlap, returns a Polygon feature representing the area they overlap; if `poly1` and `poly2` do not overlap, returns `undefined`; if `poly1` and `poly2` share a border, a MultiLineString of the locations where their borders are shared
* @example
* var poly1 = {
* "type": "Feature",
* "properties": {
* "fill": "#0f0"
* },
* "geometry": {
* "type": "Polygon",
* "coordinates": [[
* [-122.801742, 45.48565],
* [-122.801742, 45.60491],
* [-122.584762, 45.60491],
* [-122.584762, 45.48565],
* [-122.801742, 45.48565]
* ]]
* }
* }
* var poly2 = {
* "type": "Feature",
* "properties": {
* "fill": "#00f"
* },
* "geometry": {
* "type": "Polygon",
* "coordinates": [[
* [-122.520217, 45.535693],
* [-122.64038, 45.553967],
* [-122.720031, 45.526554],
* [-122.669906, 45.507309],
* [-122.723464, 45.446643],
* [-122.532577, 45.408574],
* [-122.487258, 45.477466],
* [-122.520217, 45.535693]
* ]]
* }
* }
*
* var polygons = {
* "type": "FeatureCollection",
* "features": [poly1, poly2]
* };
*
* var intersection = turf.intersect(poly1, poly2);
*
* //=polygons
*
* //=intersection
*/
module.exports = function(poly1, poly2) {
var geom1, geom2;
if(poly1.type === 'Feature') geom1 = poly1.geometry;
else geom1 = poly1;
if(poly2.type === 'Feature') geom2 = poly2.geometry;
else geom2 = poly2;
var reader = new jsts.io.GeoJSONReader();
var a = reader.read(JSON.stringify(geom1));
var b = reader.read(JSON.stringify(geom2));
var intersection = a.intersection(b);
var parser = new jsts.io.GeoJSONParser();
intersection = parser.write(intersection);
if(intersection.type === 'GeometryCollection' && intersection.geometries.length === 0) {
return undefined;
} else {
return {
type: 'Feature',
properties: {},
geometry: intersection
};
}
};