org.wamblee.gpx.GpxParser Maven / Gradle / Ivy
/*
* Copyright 2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wamblee.gpx;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.wamblee.gps.track.Track;
import org.wamblee.gps.track.TrackImpl;
import org.wamblee.gps.track.TrackPoint;
import org.wamblee.gps.track.TrackSegment;
import org.wamblee.gps.track.TrackSegmentImpl;
import org.wamblee.xml.DomUtils;
import org.wamblee.xml.XMLException;
/**
* Parser for GPX tracks.
*
* @author Erik Brakkee
*/
public class GpxParser {
private static final String SCHEMA_RESOURCE = "gpx.xsd";
public GpxParser() {
// Empty.
}
public Track parse(String aDescription, InputStream aIs) throws XMLException {
Document doc = DomUtils.convert(DomUtils.read(aIs));
return parse(aDescription, doc);
}
/**
* @param doc
*/
public Track parse(String aDescription, Document doc) {
TrackImpl result = new TrackImpl(aDescription);
List tracks = doc.getRootElement().elements("trk");
if ( tracks != null ) {
for (Element track: tracks) {
String trackName = track.elementText("name");
TrackSegmentImpl trackSegment = new TrackSegmentImpl(trackName);
result.addSegment(trackSegment);
List segments = track.elements("trkseg");
if ( segments != null ) {
for (Element segment: segments) {
parseTrackPoints(trackSegment, segment.elementIterator("trkpt"));
}
}
}
}
List routes = doc.getRootElement().elements("rte");
if ( routes != null ) {
for (Element route: routes) {
String routeName = route.elementText("desc");
TrackSegmentImpl trackSegment = new TrackSegmentImpl(routeName);
result.addSegment(trackSegment);
parseTrackPoints(trackSegment, route.elementIterator("rtept"));
}
}
return result;
}
private void parseTrackPoints(TrackSegmentImpl aTrack, Iterator aPoints) {
while (aPoints.hasNext()) {
Element point = aPoints.next();
aTrack.addPoint(parseTrackPoint(point));
}
}
/**
* @param trkpt
*/
private TrackPoint parseTrackPoint(Element trkpt) {
// System.out.println(trkpt.asXML() + "|\n");
double latitude = new Double(trkpt.attributeValue("lat"));
double longitude = new Double(trkpt.attributeValue("lon"));
Element ele = trkpt.element("ele");
double elevation = 0.0;
if (ele != null) {
elevation = new Double(ele.getText());
}
// System.out.println(" lat = " + lat + " lon = " + lon + " ele = " +
// ele);
return new TrackPoint(latitude, longitude, elevation);
}
}