]> git.argeo.org Git - gpl/argeo-suite.git/blob - org.argeo.app.core/src/org/argeo/app/geo/GpxUtils.java
Fix after changes in Argeo Commons
[gpl/argeo-suite.git] / org.argeo.app.core / src / org / argeo / app / geo / GpxUtils.java
1 package org.argeo.app.geo;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.util.ArrayList;
6 import java.util.List;
7
8 import javax.xml.parsers.ParserConfigurationException;
9 import javax.xml.parsers.SAXParser;
10 import javax.xml.parsers.SAXParserFactory;
11
12 import org.geotools.data.DataUtilities;
13 import org.geotools.feature.SchemaException;
14 import org.geotools.feature.simple.SimpleFeatureBuilder;
15 import org.geotools.geometry.jts.JTSFactoryFinder;
16 import org.locationtech.jts.geom.Coordinate;
17 import org.locationtech.jts.geom.GeometryFactory;
18 import org.locationtech.jts.geom.Polygon;
19 import org.opengis.feature.simple.SimpleFeature;
20 import org.opengis.feature.simple.SimpleFeatureType;
21 import org.xml.sax.Attributes;
22 import org.xml.sax.SAXException;
23 import org.xml.sax.helpers.DefaultHandler;
24
25 /** Utilities around the GPX format. */
26 public class GpxUtils {
27
28 public static SimpleFeature parseGpxToPolygon(InputStream in) {
29 try {
30 final SimpleFeatureType TYPE = DataUtilities.createType("Area", "the_geom:Polygon:srid=4326");
31 SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
32
33 GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
34 List<Coordinate> coordinates = new ArrayList<>();
35 SAXParserFactory factory = SAXParserFactory.newInstance();
36 Double[] startCoord = new Double[2];
37 SAXParser saxParser = factory.newSAXParser();
38
39 saxParser.parse(in, new DefaultHandler() {
40
41 @Override
42 public void startElement(String uri, String localName, String qName, Attributes attributes)
43 throws SAXException {
44 if ("trkpt".equals(qName)) {
45 Double latitude = Double.parseDouble(attributes.getValue("lat"));
46 Double longitude = Double.parseDouble(attributes.getValue("lon"));
47 Coordinate coordinate = new Coordinate(longitude, latitude);
48 coordinates.add(coordinate);
49 }
50 }
51
52 });
53 // close the line string
54 coordinates.add(coordinates.get(0));
55
56 Polygon polygon = geometryFactory.createPolygon(coordinates.toArray(new Coordinate[coordinates.size()]));
57 featureBuilder.add(polygon);
58 SimpleFeature area = featureBuilder.buildFeature(null);
59 return area;
60 } catch (ParserConfigurationException | SAXException | IOException | SchemaException e) {
61 throw new RuntimeException("Cannot convert GPX", e);
62 }
63 }
64
65 /** Singleton. */
66 private GpxUtils() {
67 }
68 }