-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathExportAOI.js
More file actions
482 lines (433 loc) · 13.2 KB
/
ExportAOI.js
File metadata and controls
482 lines (433 loc) · 13.2 KB
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
import bbox from "@turf/bbox";
import PropTypes from "prop-types";
import React, { Component } from "react";
import { connect } from "react-redux";
import Attribution from "ol/control/attribution";
import Draw from "ol/interaction/draw";
import Feature from "ol/feature";
import { feature, featureCollection, polygon } from "@turf/helpers";
import Fill from "ol/style/fill";
import GeoJSONFormat from "ol/format/geojson";
import interaction from "ol/interaction";
import LayerAttribution from "ol/attribution";
import Map from "ol/map";
import OSM from "ol/source/osm";
import Polygon from "ol/geom/polygon";
import proj from "ol/proj";
import RegularShape from "ol/style/regularshape";
import ScaleLine from "ol/control/scaleline";
import Stroke from "ol/style/stroke";
import Style from "ol/style/style";
import Tile from "ol/layer/tile";
import VectorLayer from "ol/layer/vector";
import VectorSource from "ol/source/vector";
import View from "ol/view";
import Zoom from "ol/control/zoom";
import styles from "../../styles/aoi/CreateExport.css";
import AoiInfobar from "./AoiInfobar.js";
import SearchAOIToolbar from "./SearchAOIToolbar.js";
import DrawAOIToolbar from "./DrawAOIToolbar.js";
import InvalidDrawWarning from "./InvalidDrawWarning.js";
import DropZone from "./DropZone.js";
import ZoomExtent from "../ZoomExtent";
import { updateMode } from "../../actions/exports";
export const MODE_DRAW_BBOX = "MODE_DRAW_BBOX";
export const MODE_NORMAL = "MODE_NORMAL";
export const MODE_DRAW_FREE = "MODE_DRAW_FREE";
const WGS84 = "EPSG:4326";
const WEB_MERCATOR = "EPSG:3857";
const isEqual = require("lodash/isEqual");
const GEOJSON_FORMAT = new GeoJSONFormat();
export class ExportAOI extends Component {
static propTypes = {
aoi: PropTypes.shape({
description: PropTypes.string,
geojson: PropTypes.object,
geomType: PropTypes.string,
title: PropTypes.string
}),
errors: PropTypes.any,
mode: PropTypes.string,
importGeom: PropTypes.object,
updateMode: PropTypes.func,
updateAoiInfo: PropTypes.func,
clearAoiInfo: PropTypes.func,
};
getFeature(geojson) {
switch (geojson.type) {
case "FeatureCollection":
return GEOJSON_FORMAT.readFeature(geojson.features[0], {
dataProjection: WGS84,
featureProjection: WEB_MERCATOR
});
case "Feature":
return GEOJSON_FORMAT.readFeature(geojson, {
dataProjection: WGS84,
featureProjection: WEB_MERCATOR
});
default:
return new Feature({
geometry: GEOJSON_FORMAT.readGeometry(geojson, {
dataProjection: WGS84,
featureProjection: WEB_MERCATOR
})
});
}
}
componentDidMount() {
const { aoi: { geojson } } = this.props;
this._initializeOpenLayers();
this._updateInteractions();
if (geojson != null && Object.keys(geojson).length > 0) {
const feature = this.getFeature(geojson);
this._drawLayer.getSource().addFeature(feature);
this.handleZoomToSelection(serialize(feature.getGeometry().getExtent()));
}
}
componentDidUpdate(prevProps, prevState) {
if (!isEqual(prevProps.aoi.geojson, this.props.aoi.geojson)) {
// remove existing features
this._clearDraw();
if (this.props.aoi.geojson) {
const feature = this.getFeature(this.props.aoi.geojson);
this._drawLayer.getSource().addFeature(feature);
this.handleZoomToSelection(bbox(this.props.aoi.geojson));
}
}
}
componentWillReceiveProps(nextProps) {
// Check if the map mode has changed (DRAW or NORMAL)
if (this.props.mode !== nextProps.mode) {
this._updateInteractions(nextProps.mode);
}
if (nextProps.importGeom.processed && !this.props.importGeom.processed) {
this.handleGeoJSONUpload(nextProps.importGeom.geojson);
}
}
handleCancel = sender => {
if (this.props.mode !== MODE_NORMAL) {
this.props.updateMode(MODE_NORMAL);
}
this._clearDraw();
this.props.clearAoiInfo();
};
handleZoomToSelection = bbox =>
this._map
.getView()
.fit(
proj.transformExtent(bbox, WGS84, WEB_MERCATOR),
this._map.getSize()
);
handleSearch = result => {
var geojson;
if (result.adminName2 && result.adminName2.startsWith('ISO3')){
try {
geojson = JSON.parse(JSON.stringify(result.bbox));
} catch (e) {
alert(e);
}
// extract single feature geometry from collection
if (geojson.type === "FeatureCollection") {
if (geojson.features.length === 1) {
geojson = geojson.features[0].geometry;
}
}
if (["Polygon", "MultiPolygon"].includes(geojson.type)) {
geojson = featureCollection([feature(geojson)]);
}
}
else if (result.adminName2 == 'TM' || result.adminName2 == 'OSM') {
this._clearDraw();
geojson = result.bbox;
}
else {
const unformattedBbox = result.bbox;
const formattedBbox = [
unformattedBbox.west,
unformattedBbox.south,
unformattedBbox.east,
unformattedBbox.north
];
this._clearDraw();
const bbox = formattedBbox.map(truncate);
const mercBbox = proj.transformExtent(bbox, WGS84, WEB_MERCATOR);
const geom = Polygon.fromExtent(mercBbox);
geojson = createGeoJSON(geom);
const bboxFeature = new Feature({
geometry: geom
});
}
//this._drawLayer.getSource().addFeature(bboxFeature);
let description = "";
description += result.countryName ? result.countryName : "";
description += result.adminName1 ? ", " + result.adminName1 : "";
description += result.adminName2 ? ", " + result.adminName2 : "";
this.props.updateAoiInfo(geojson, "Polygon", result.name, description);
this.handleZoomToSelection(bbox);
};
handleSearchNominatim = result => {
this.props.updateAoiInfo(result.geojson, "Polygon", result.name, result.description);
}
handleGeoJSONUpload = geojson =>
this.props.updateAoiInfo(geojson, "Polygon", "Custom Polygon", "Import");
setMapView = () => {
this._clearDraw();
const extent = this._map.getView().calculateExtent(this._map.getSize());
const geom = Polygon.fromExtent(extent);
const geojson = createGeoJSON(geom);
this.props.updateAoiInfo(geojson, "Polygon", "Custom Polygon", "Map View");
};
_activateDrawInteraction(mode) {
if (mode === MODE_DRAW_BBOX) {
this._drawFreeInteraction.setActive(false);
this._drawBoxInteraction.setActive(true);
} else if (mode === MODE_DRAW_FREE) {
this._drawBoxInteraction.setActive(false);
this._drawFreeInteraction.setActive(true);
}
}
_clearDraw() {
this._drawLayer.getSource().clear();
}
_deactivateDrawInteraction() {
this._drawBoxInteraction.setActive(false);
this._drawFreeInteraction.setActive(false);
}
_handleDrawEnd = event => {
// get the drawn bounding box
const geometry = event.feature.getGeometry();
const geojson = createGeoJSON(geometry);
this.props.updateAoiInfo(geojson, "Polygon", "Custom Polygon", "Draw");
this.props.updateMode("MODE_NORMAL");
};
_handleDrawStart = () => this._clearDraw();
_initializeOpenLayers() {
this._drawLayer = generateDrawLayer();
this._drawBoxInteraction = _generateDrawBoxInteraction(this._drawLayer);
this._drawBoxInteraction.on("drawstart", this._handleDrawStart);
this._drawBoxInteraction.on("drawend", this._handleDrawEnd);
this._drawFreeInteraction = _generateDrawFreeInteraction(this._drawLayer);
this._drawFreeInteraction.on("drawstart", this._handleDrawStart);
this._drawFreeInteraction.on("drawend", this._handleDrawEnd);
this._map = new Map({
controls: [
new ScaleLine({
className: styles.olScaleLine
}),
new Attribution({
collapsible: false,
collapsed: false
}),
new Zoom({
className: styles.olZoom
}),
new ZoomExtent({
className: styles.olZoomToExtent,
extent: [
-14251567.50789682,
-10584983.780136958,
14251787.50789682,
10584983.780136958
]
})
],
interactions: interaction.defaults({
keyboard: false,
altShiftDragRotate: false,
pinchRotate: false
}),
layers: [
// Order matters here
new Tile({
source: new OSM({
attributions: [
new LayerAttribution({
html: `© <a href="https://osm.org/">OSM</a>`
}),
OSM.ATTRIBUTION
],
crossOrigin: null,
url:
"https://tile.openstreetmap.org/{z}/{x}/{y}.png"
})
})
],
target: "map",
view: new View({
projection: "EPSG:3857",
center: [110, 0],
zoom: 2,
minZoom: 2,
maxZoom: 22
})
});
this._map.addInteraction(this._drawBoxInteraction);
this._map.addInteraction(this._drawFreeInteraction);
this._map.addLayer(this._drawLayer);
}
zoomToSelection = () => {
const { aoi: { geojson } } = this.props;
this.handleZoomToSelection(bbox(geojson));
};
render() {
const { aoi, aoi: { geojson }, errors } = this.props;
return (
<div>
<div id="map" className={styles.map} ref="olmap">
{geojson &&
<AoiInfobar aoi={aoi} zoomToSelection={this.zoomToSelection} />}
<SearchAOIToolbar
handleSearch={this.handleSearch}
handleSearchNominatim={this.handleSearchNominatim}
handleCancel={this.handleCancel}
/>
<DrawAOIToolbar
handleCancel={this.handleCancel}
setMapView={this.setMapView}
/>
<InvalidDrawWarning msg={errors} />
<DropZone />
</div>
</div>
);
}
_updateInteractions(mode) {
switch (mode) {
case MODE_DRAW_BBOX:
this._activateDrawInteraction(MODE_DRAW_BBOX);
break;
case MODE_DRAW_FREE:
this._activateDrawInteraction(MODE_DRAW_FREE);
break;
case MODE_NORMAL:
this._deactivateDrawInteraction();
break;
default:
console.warn("Unrecognized interaction mode:", mode);
}
}
}
function mapStateToProps(state) {
return {
mode: state.mode,
zoomToSelection: state.zoomToSelection,
importGeom: state.importGeom
};
}
export default connect(mapStateToProps, {
updateMode,
})(ExportAOI);
function generateDrawLayer() {
return new VectorLayer({
source: new VectorSource({
wrapX: false
}),
style: new Style({
fill: new Fill({
color: "hsla(202, 70%, 50%, .35)"
}),
stroke: new Stroke({
color: "hsla(202, 70%, 50%, .7)",
width: 1,
lineDash: [5, 5]
})
})
});
}
function _generateDrawBoxInteraction(drawLayer) {
const draw = new Draw({
source: drawLayer.getSource(),
maxPoints: 2,
type: "LineString",
geometryFunction(coordinates, geometry) {
geometry = geometry || new Polygon(null);
const [[x1, y1], [x2, y2]] = coordinates;
geometry.setCoordinates([
[[x1, y1], [x1, y2], [x2, y2], [x2, y1], [x1, y1]]
]);
return geometry;
},
style: new Style({
image: new RegularShape({
stroke: new Stroke({
color: "black",
width: 1
}),
points: 4,
radius: 15,
radius2: 0,
angle: 0
}),
fill: new Fill({
color: "hsla(202, 70%, 50%, .6)"
}),
stroke: new Stroke({
color: "hsl(202, 70%, 50%)",
width: 1,
lineDash: [5, 5]
})
})
});
draw.setActive(false);
return draw;
}
function _generateDrawFreeInteraction(drawLayer) {
const draw = new Draw({
source: drawLayer.getSource(),
type: "Polygon",
freehand: false,
style: new Style({
image: new RegularShape({
stroke: new Stroke({
color: "black",
width: 1
}),
points: 4,
radius: 15,
radius2: 0,
angle: 0
}),
fill: new Fill({
color: "hsla(202, 70%, 50%, .6)"
}),
stroke: new Stroke({
color: "hsl(202, 70%, 50%)",
width: 1,
lineDash: [5, 5]
})
})
});
draw.setActive(false);
return draw;
}
function truncate(number) {
return Math.round(number * 100) / 100;
}
function unwrapPoint([x, y]) {
return [x > 0 ? Math.min(180, x) : Math.max(-180, x), y];
}
function serialize(extent) {
const bbox = proj.transformExtent(extent, WEB_MERCATOR, WGS84);
const p1 = unwrapPoint(bbox.slice(0, 2));
const p2 = unwrapPoint(bbox.slice(2, 4));
return p1.concat(p2).map(truncate);
}
function createGeoJSON(ol3Geometry) {
const bbox = serialize(ol3Geometry.getExtent());
const coords = ol3Geometry.getCoordinates();
// need to apply transform to a cloned geom but simple geometry does not support .clone() operation.
const polygonGeom = new Polygon(coords);
polygonGeom.transform(WEB_MERCATOR, WGS84);
const wgs84Coords = polygonGeom.getCoordinates();
const geojson = {
type: "FeatureCollection",
features: [
{
type: "Feature",
bbox: bbox,
geometry: { type: "Polygon", coordinates: wgs84Coords }
}
]
};
return geojson;
}