1 package org
.argeo
.app
.geo
;
3 import java
.io
.IOException
;
4 import java
.io
.InputStream
;
5 import java
.util
.ArrayList
;
8 import javax
.xml
.parsers
.ParserConfigurationException
;
9 import javax
.xml
.parsers
.SAXParser
;
10 import javax
.xml
.parsers
.SAXParserFactory
;
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
;
25 /** Utilities around the GPX format. */
26 public class GpxUtils
{
28 public static SimpleFeature
parseGpxToPolygon(InputStream in
) {
30 final SimpleFeatureType TYPE
= DataUtilities
.createType("Area", "the_geom:Polygon:srid=4326");
31 SimpleFeatureBuilder featureBuilder
= new SimpleFeatureBuilder(TYPE
);
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();
39 saxParser
.parse(in
, new DefaultHandler() {
42 public void startElement(String uri
, String localName
, String qName
, Attributes attributes
)
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
);
53 // close the line string
54 coordinates
.add(coordinates
.get(0));
56 Polygon polygon
= geometryFactory
.createPolygon(coordinates
.toArray(new Coordinate
[coordinates
.size()]));
57 featureBuilder
.add(polygon
);
58 SimpleFeature area
= featureBuilder
.buildFeature(null);
60 } catch (ParserConfigurationException
| SAXException
| IOException
| SchemaException e
) {
61 throw new RuntimeException("Cannot convert GPX", e
);