]> git.argeo.org Git - gpl/argeo-suite.git/blob - geo/GpxUtils.java
Prepare next development cycle
[gpl/argeo-suite.git] / 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 SAXParser saxParser = factory.newSAXParser();
37
38 saxParser.parse(in, new DefaultHandler() {
39
40 @Override
41 public void startElement(String uri, String localName, String qName, Attributes attributes)
42 throws SAXException {
43 if ("trkpt".equals(qName)) {
44 Double latitude = Double.parseDouble(attributes.getValue("lat"));
45 Double longitude = Double.parseDouble(attributes.getValue("lon"));
46 Coordinate coordinate = new Coordinate(longitude, latitude);
47 coordinates.add(coordinate);
48 }
49 }
50
51 });
52 // close the line string
53 coordinates.add(coordinates.get(0));
54
55 Polygon polygon = geometryFactory.createPolygon(coordinates.toArray(new Coordinate[coordinates.size()]));
56 featureBuilder.add(polygon);
57 SimpleFeature area = featureBuilder.buildFeature(null);
58 return area;
59 } catch (ParserConfigurationException | SAXException | IOException | SchemaException e) {
60 throw new RuntimeException("Cannot convert GPX", e);
61 }
62 }
63
64 /** Singleton. */
65 private GpxUtils() {
66 }
67 }