-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
96 lines (91 loc) · 2.38 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// depend on jsts for now https://github.com/bjornharrtell/jsts/blob/master/examples/overlay.html
var jsts = require('jsts');
/**
* Finds the difference between two {@link Polygon|polygons} by clipping the second
* polygon from the first.
*
* @module turf/difference
* @category transformation
* @param {Feature<Polygon>} poly1 input Polygon feaure
* @param {Feature<Polygon>} poly2 Polygon feature to difference from `poly1`
* @return {Feature<Polygon>} a Polygon feature showing the area of `poly1` excluding the area of `poly2`
* @example
* var poly1 = {
* "type": "Feature",
* "properties": {
* "fill": "#0f0"
* },
* "geometry": {
* "type": "Polygon",
* "coordinates": [[
* [-46.738586, -23.596711],
* [-46.738586, -23.458207],
* [-46.560058, -23.458207],
* [-46.560058, -23.596711],
* [-46.738586, -23.596711]
* ]]
* }
* };
* var poly2 = {
* "type": "Feature",
* "properties": {
* "fill": "#00f"
* },
* "geometry": {
* "type": "Polygon",
* "coordinates": [[
* [-46.650009, -23.631314],
* [-46.650009, -23.5237],
* [-46.509246, -23.5237],
* [-46.509246, -23.631314],
* [-46.650009, -23.631314]
* ]]
* }
* };
*
* var differenced = turf.difference(poly1, poly2);
* differenced.properties.fill = '#f00';
*
* var polygons = {
* "type": "FeatureCollection",
* "features": [poly1, poly2]
* };
*
* //=polygons
*
* //=differenced
*/
module.exports = function(p1, p2) {
var poly1 = JSON.parse(JSON.stringify(p1));
var poly2 = JSON.parse(JSON.stringify(p2));
if(poly1.type !== 'Feature') {
poly1 = {
type: 'Feature',
properties: {},
geometry: poly1
};
}
if(poly2.type !== 'Feature') {
poly2 = {
type: 'Feature',
properties: {},
geometry: poly2
};
}
var reader = new jsts.io.GeoJSONReader();
var a = reader.read(JSON.stringify(poly1.geometry));
var b = reader.read(JSON.stringify(poly2.geometry));
var differenced = a.difference(b);
var parser = new jsts.io.GeoJSONParser();
differenced = parser.write(differenced);
poly1.geometry = differenced;
if (poly1.geometry.type === 'GeometryCollection' && poly1.geometry.geometries.length === 0) {
return undefined;
} else {
return {
type: 'Feature',
properties: poly1.properties,
geometry: differenced
};
}
};