1
|
/**
|
2
|
* Copyright (C) 2020 EDIT
|
3
|
* European Distributed Institute of Taxonomy
|
4
|
* http://www.e-taxonomy.eu
|
5
|
*
|
6
|
* The contents of this file are subject to the Mozilla Public License Version 1.1
|
7
|
* See LICENSE.TXT at the top of this package for the full license terms.
|
8
|
*/
|
9
|
|
10
|
package eu.etaxonomy.cdm.ext.geo.kml;
|
11
|
|
12
|
import java.util.ArrayList;
|
13
|
import java.util.Arrays;
|
14
|
import java.util.HashMap;
|
15
|
import java.util.HashSet;
|
16
|
import java.util.List;
|
17
|
import java.util.Map;
|
18
|
import java.util.Optional;
|
19
|
import java.util.Set;
|
20
|
|
21
|
import org.apache.commons.lang3.StringUtils;
|
22
|
import org.apache.logging.log4j.LogManager;
|
23
|
import org.apache.logging.log4j.Logger;
|
24
|
import org.geotools.feature.SchemaException;
|
25
|
import org.locationtech.jts.geom.Coordinate;
|
26
|
import org.opengis.feature.simple.SimpleFeature;
|
27
|
import org.opengis.referencing.FactoryException;
|
28
|
|
29
|
import de.micromata.opengis.kml.v_2_2_0.AltitudeMode;
|
30
|
import de.micromata.opengis.kml.v_2_2_0.Document;
|
31
|
import de.micromata.opengis.kml.v_2_2_0.ExtendedData;
|
32
|
import de.micromata.opengis.kml.v_2_2_0.Feature;
|
33
|
import de.micromata.opengis.kml.v_2_2_0.Kml;
|
34
|
import de.micromata.opengis.kml.v_2_2_0.KmlFactory;
|
35
|
import de.micromata.opengis.kml.v_2_2_0.LineStyle;
|
36
|
import de.micromata.opengis.kml.v_2_2_0.LinearRing;
|
37
|
import de.micromata.opengis.kml.v_2_2_0.Placemark;
|
38
|
import de.micromata.opengis.kml.v_2_2_0.PolyStyle;
|
39
|
import de.micromata.opengis.kml.v_2_2_0.Polygon;
|
40
|
import de.micromata.opengis.kml.v_2_2_0.Style;
|
41
|
import eu.etaxonomy.cdm.model.location.Point;
|
42
|
import eu.etaxonomy.cdm.model.occurrence.DerivedUnit;
|
43
|
import eu.etaxonomy.cdm.model.occurrence.FieldUnit;
|
44
|
import eu.etaxonomy.cdm.model.occurrence.GatheringEvent;
|
45
|
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
|
46
|
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationType;
|
47
|
import eu.etaxonomy.cdm.model.term.DefinedTerm;
|
48
|
import eu.etaxonomy.cdm.model.term.TermType;
|
49
|
import si.uom.SI;
|
50
|
import tec.uom.se.quantity.Quantities;
|
51
|
|
52
|
/**
|
53
|
*
|
54
|
* @author Andreas Kohlbecker
|
55
|
* @since Apr 21, 2020
|
56
|
*/
|
57
|
public class KMLDocumentBuilder {
|
58
|
|
59
|
private final static Logger logger = LogManager.getLogger(KMLDocumentBuilder.class);
|
60
|
|
61
|
private Set<SpecimenOrObservationBase> occSet = new HashSet<>();
|
62
|
|
63
|
private Map<FieldUnit, Set<SpecimenOrObservationBase>> fieldUnitMap = new HashMap<>();
|
64
|
private Map<FieldUnit, Set<SpecimenOrObservationType>> fieldUnitRecordBases = new HashMap<>();
|
65
|
|
66
|
private Map<String, Style> styles = new HashMap<>();
|
67
|
|
68
|
private static final DefinedTerm KIND_OF_UNIT_UNSET = DefinedTerm.NewInstance(TermType.KindOfUnit);
|
69
|
|
70
|
public KMLDocumentBuilder addSpecimenOrObservationBase(SpecimenOrObservationBase occurrence) {
|
71
|
occSet.add(occurrence);
|
72
|
return this;
|
73
|
}
|
74
|
|
75
|
public Kml build() {
|
76
|
|
77
|
Kml kml = KmlFactory.createKml();
|
78
|
List<Feature> documentFeatures = new ArrayList<>();
|
79
|
|
80
|
for (SpecimenOrObservationBase sob : occSet) {
|
81
|
mapFieldUnit(sob, null, null);
|
82
|
}
|
83
|
for (FieldUnit fu : fieldUnitMap.keySet()) {
|
84
|
createFieldUnitPlacemarks(documentFeatures, fu);
|
85
|
}
|
86
|
|
87
|
Document doc = kml.createAndSetDocument();
|
88
|
doc.getFeature().addAll(documentFeatures);
|
89
|
doc.getStyleSelector().addAll(styles.values());
|
90
|
return kml;
|
91
|
}
|
92
|
|
93
|
private void mapFieldUnit(SpecimenOrObservationBase unitOfInterest, SpecimenOrObservationBase original, Set<SpecimenOrObservationType> recordBases) {
|
94
|
|
95
|
if(original == null) {
|
96
|
original = unitOfInterest;
|
97
|
}
|
98
|
if(recordBases == null) {
|
99
|
recordBases = new HashSet<>();
|
100
|
}
|
101
|
|
102
|
if (original instanceof FieldUnit) {
|
103
|
FieldUnit fu = (FieldUnit)original;
|
104
|
if(!fieldUnitMap.containsKey(fu)) {
|
105
|
fieldUnitMap.put(fu, new HashSet<>());
|
106
|
}
|
107
|
fieldUnitMap.get(fu).add(unitOfInterest);
|
108
|
if(!fieldUnitRecordBases.containsKey(fu)) {
|
109
|
fieldUnitRecordBases.put(fu, new HashSet<>());
|
110
|
}
|
111
|
fieldUnitRecordBases.get(fu).addAll(recordBases);
|
112
|
} else if (original instanceof DerivedUnit) {
|
113
|
Set<SpecimenOrObservationBase> originals = ((DerivedUnit)original).getOriginals();
|
114
|
if (originals != null) {
|
115
|
for (SpecimenOrObservationBase parentOriginal : originals) {
|
116
|
mapFieldUnit(original, parentOriginal, recordBases);
|
117
|
}
|
118
|
}
|
119
|
}
|
120
|
}
|
121
|
|
122
|
private void createFieldUnitPlacemarks(List<Feature> documentFeatures, FieldUnit fieldUnit) {
|
123
|
|
124
|
GatheringEvent gatherEvent = fieldUnit.getGatheringEvent();
|
125
|
if (gatherEvent != null && isValidPoint(gatherEvent.getExactLocation())) {
|
126
|
Placemark mapMarker = fieldUnitLocationMarker(gatherEvent.getExactLocation(),
|
127
|
gatherEvent.getAbsoluteElevation(), fieldUnitRecordBases.get(fieldUnit));
|
128
|
documentFeatures.add(mapMarker);
|
129
|
addExtendedData(mapMarker, fieldUnit, gatherEvent);
|
130
|
errorRadiusPlacemark(gatherEvent.getExactLocation()).ifPresent(pm -> documentFeatures.add(pm));
|
131
|
}
|
132
|
}
|
133
|
|
134
|
private Placemark fieldUnitLocationMarker(Point exactLocation, Integer altitude, Set<SpecimenOrObservationType> recordBases) {
|
135
|
|
136
|
Placemark mapMarker = KmlFactory.createPlacemark();
|
137
|
de.micromata.opengis.kml.v_2_2_0.Point point = KmlFactory.createPoint();
|
138
|
point.setAltitudeMode(AltitudeMode.ABSOLUTE);
|
139
|
if (altitude != null) {
|
140
|
point.setCoordinates(Arrays.asList(KmlFactory.createCoordinate(exactLocation.getLongitude(),
|
141
|
exactLocation.getLatitude(), altitude.doubleValue())));
|
142
|
} else {
|
143
|
point.setCoordinates(Arrays
|
144
|
.asList(KmlFactory.createCoordinate(exactLocation.getLongitude(), exactLocation.getLatitude())));
|
145
|
}
|
146
|
mapMarker.setGeometry(point);
|
147
|
mapMarker.setStyleUrl(styleURL(recordBases));
|
148
|
|
149
|
return mapMarker;
|
150
|
}
|
151
|
|
152
|
private Optional<Placemark> errorRadiusPlacemark(Point exactLocation) {
|
153
|
|
154
|
// exactLocation.setErrorRadius(25 * 1000); // METER // uncomment for debugging
|
155
|
|
156
|
Placemark errorRadiusCicle = null;
|
157
|
if (exactLocation.getErrorRadius() != null && exactLocation.getErrorRadius() > 0) {
|
158
|
errorRadiusCicle = KmlFactory.createPlacemark();
|
159
|
LinearRing cirle = createKMLCircle(exactLocation.getLongitude(), exactLocation.getLatitude(),
|
160
|
exactLocation.getErrorRadius());
|
161
|
Polygon polygon = errorRadiusCicle.createAndSetPolygon();
|
162
|
polygon.createAndSetOuterBoundaryIs().setLinearRing(cirle);
|
163
|
polygon.setExtrude(true);
|
164
|
errorRadiusCicle.setStyleUrl(errorRadiusStyleURL());
|
165
|
}
|
166
|
|
167
|
return Optional.ofNullable(errorRadiusCicle);
|
168
|
}
|
169
|
|
170
|
|
171
|
/**
|
172
|
* @param longitude
|
173
|
* @param latitude
|
174
|
* @param errorRadiusMeter
|
175
|
* @return
|
176
|
*/
|
177
|
private LinearRing createKMLCircle(Double longitude, Double latitude, Integer errorRadiusMeter) {
|
178
|
|
179
|
GeometryBuilder.CircleMethod method = GeometryBuilder.CircleMethod.reprojectedCircle;
|
180
|
LinearRing lineString = KmlFactory.createLinearRing();
|
181
|
lineString.setAltitudeMode(AltitudeMode.RELATIVE_TO_GROUND);
|
182
|
|
183
|
org.locationtech.jts.geom.Geometry polygonGeom = null;
|
184
|
GeometryBuilder gb = new GeometryBuilder();
|
185
|
try {
|
186
|
switch (method) {
|
187
|
case simpleCircle:
|
188
|
// this is the best method so far !!!!
|
189
|
polygonGeom = gb.simpleCircle(Quantities.getQuantity(errorRadiusMeter.doubleValue(), SI.METRE),
|
190
|
latitude, longitude);
|
191
|
break;
|
192
|
case simpleCircleSmall:
|
193
|
// Only suitable for small radius (> 1000 m) as the circles are heavily distorted
|
194
|
// otherwise.
|
195
|
polygonGeom = gb.simpleCircleSmall(errorRadiusMeter.doubleValue(), latitude, longitude);
|
196
|
break;
|
197
|
case circle:
|
198
|
// fails
|
199
|
polygonGeom = gb.circle(errorRadiusMeter.doubleValue(), latitude, longitude);
|
200
|
break;
|
201
|
case reprojectedCircle:
|
202
|
// incomplete
|
203
|
SimpleFeature pointFeature = gb.createSimplePointFeature(longitude, latitude);
|
204
|
polygonGeom = gb.bufferFeature(pointFeature, errorRadiusMeter.doubleValue());
|
205
|
break;
|
206
|
}
|
207
|
for (Coordinate coordinate : polygonGeom.getCoordinates()) {
|
208
|
lineString.addToCoordinates(coordinate.getX(), coordinate.getY());
|
209
|
}
|
210
|
} catch (FactoryException e) {
|
211
|
logger.error("Polygon creation for error radius failed", e);
|
212
|
} catch (SchemaException e) {
|
213
|
logger.error("SimplePointFeature creation failed", e);
|
214
|
}
|
215
|
return lineString;
|
216
|
}
|
217
|
|
218
|
private void addExtendedData(Placemark mapMarker, FieldUnit fieldUnit, GatheringEvent gatherEvent) {
|
219
|
|
220
|
String name = fieldUnit.toString();
|
221
|
String titleCache = fieldUnit.getTitleCache();
|
222
|
String locationString = null;
|
223
|
if(gatherEvent.getExactLocation() != null) {
|
224
|
locationString = gatherEvent.getExactLocation().toSexagesimalString(false, true);
|
225
|
titleCache = titleCache.replace(locationString + ", ", "");
|
226
|
}
|
227
|
String description = "<p class=\"title-cache\">" + titleCache;
|
228
|
if(locationString != null) {
|
229
|
// see https://www.mediawiki.org/wiki/GeoHack
|
230
|
String geohackUrl = String.format(
|
231
|
"https://geohack.toolforge.org/geohack.php?language=en¶ms=%f;%f&pagename=%s",
|
232
|
gatherEvent.getExactLocation().getLatitude(),
|
233
|
gatherEvent.getExactLocation().getLongitude(),
|
234
|
name);
|
235
|
description += "<br/><a class=\"exact-location\" target=\"geohack\" href=\"" + geohackUrl + "\">" + locationString + "</a>";
|
236
|
}
|
237
|
description += "</p>";
|
238
|
description += "<figure><figcaption>Specimens and observations:</figcaption><ul>";
|
239
|
for(SpecimenOrObservationBase sob : fieldUnitMap.get(fieldUnit)) {
|
240
|
SpecimenOrObservationType type = sob.getRecordBasis() != null ? sob.getRecordBasis() : SpecimenOrObservationType.Unknown;
|
241
|
String unitTitle = type.name();
|
242
|
if(sob instanceof DerivedUnit) {
|
243
|
DerivedUnit du = ((DerivedUnit)sob);
|
244
|
if(StringUtils.isNotBlank(du.getMostSignificantIdentifier())){
|
245
|
unitTitle += ": " + du.getMostSignificantIdentifier();
|
246
|
}
|
247
|
}
|
248
|
description += "<li><a class=\"occurrence-link occurrence-link-" + sob.getUuid() + " \" href=\"${occurrence-link-base-url}/" + sob.getUuid() + "\">" + unitTitle + "</a></li>";
|
249
|
}
|
250
|
description += "</ul></figure>";
|
251
|
// mapMarker.setName(name);
|
252
|
mapMarker.setDescription(description);
|
253
|
|
254
|
ExtendedData extendedData = mapMarker.createAndSetExtendedData();
|
255
|
extendedData.createAndAddData(fieldUnit.getTitleCache()).setName("titleCache");
|
256
|
if(mapMarker.getGeometry() != null && mapMarker.getGeometry() instanceof de.micromata.opengis.kml.v_2_2_0.Point) {
|
257
|
extendedData.createAndAddData(((de.micromata.opengis.kml.v_2_2_0.Point)mapMarker.getGeometry()).getCoordinates().toString()).setName("Location");
|
258
|
}
|
259
|
|
260
|
}
|
261
|
|
262
|
|
263
|
private String styleURL(Set<SpecimenOrObservationType> recordBases) {
|
264
|
String key = "DEFAULT";
|
265
|
// TODO determine key and style on base of the recordBases
|
266
|
if (!styles.containsKey(key)) {
|
267
|
Style style = KmlFactory.createStyle().withIconStyle(MapMarkerIcons.red_blank.asIconStyle());
|
268
|
style.setId(key);
|
269
|
styles.put(key, style);
|
270
|
}
|
271
|
return "#" + key;
|
272
|
}
|
273
|
|
274
|
private String errorRadiusStyleURL() {
|
275
|
String key = "ERROR_RADIUS";
|
276
|
if (!styles.containsKey(key)) {
|
277
|
Style style = KmlFactory.createStyle();
|
278
|
PolyStyle polyStyle = style.createAndSetPolyStyle();
|
279
|
polyStyle.setColor("100000ee"); // aabbggrr, where aa=alpha (00 to ff); bb=blue (00 to ff); gg=green (00 to ff); rr=red (00 to ff).
|
280
|
polyStyle.setFill(true);
|
281
|
polyStyle.setOutline(true);
|
282
|
style.setId(key);
|
283
|
LineStyle lineStyle = style.createAndSetLineStyle();
|
284
|
// lineStyle.setColor("ff880088"); // aabbggrr, where aa=alpha (00 to ff);
|
285
|
// bb=blue (00 to ff); gg=green (00 to ff); rr=red (00 to ff).
|
286
|
lineStyle.setWidth(1);
|
287
|
styles.put(key, style);
|
288
|
}
|
289
|
return "#" + key;
|
290
|
}
|
291
|
|
292
|
|
293
|
// TODO use also for .EditGeoService.registerDerivedUnitLocations(DerivedUnit
|
294
|
// derivedUnit, List<Point> derivedUnitPoints) !!!!!!!!!
|
295
|
public boolean isValidPoint(Point point) {
|
296
|
|
297
|
if (point == null) {
|
298
|
return false;
|
299
|
}
|
300
|
// points with no longitude or latitude should not exist
|
301
|
// see #4173 ([Rule] Longitude and Latitude in Point must not be null)
|
302
|
if (point.getLatitude() == null || point.getLongitude() == null) {
|
303
|
return false;
|
304
|
}
|
305
|
// FIXME: remove next statement after
|
306
|
// DerivedUnitFacade or ABCD import is fixed
|
307
|
//
|
308
|
if (point.getLatitude() == 0.0 || point.getLongitude() == 0.0) {
|
309
|
return false;
|
310
|
}
|
311
|
return true;
|
312
|
}
|
313
|
}
|