Parsing local gpx file in Android

7.7k views Asked by At

I followed this example to parse a local GPX file in Android: http://android-coding.blogspot.pt/2013/01/get-latitude-and-longitude-from-gpx-file.html

All works fine to access "lat" and "long" but I need also to get the "ele" value but all my tentatives were unsuccessful. Anyone can give me some hits to do that?

Thanks in advance! Best regards, NR.

4

There are 4 answers

0
goojr On BEST ANSWER

you have the "Node node = nodelist_trkpt.item(i);" in your first loop. Get the child elements from this node an run through these child elements.

e.g.:

NodeList nList = node.getChildNodes();
for(int j=0; j<nList.getLength(); j++) {
    Node el = nList.item(j);
    if(el.getNodeName().equals("ele")) {
     System.out.println(el.getTextContent());
  }
}
0
kamituel On

Update: I've added parsing "ele" element as well, so this code could match your requirements.

I will propose different approach: https://gist.github.com/kamituel/6465125.

In my approach I don't create an ArrayList of all track points (this is done in the example you posted). Such a list can consume quite a lot of memory, which can be an issue on Android.

I've even given up on using regex parsing to avoid allocating too many objects (which causes garbage collector to run).

As a result, running Java with 16Mb heap size, parsing GPX file with over 600 points, garbage collector will be run only 12 times. I'm sure one could go lower, but I didn't optimize it heavily yet.

Usage:

GpxParser parser = new GpxParser(new FileInputStream(file));
TrkPt point = null;
while ((point = parser.nextTrkPt()) != null) {
  // point.getLat()
  // point.getLon()
}

I've successfully used this code to parse around 100 Mb of GPX files on Android. Sorry it's not in the regular repo, I didn't plan to share it just yet.

2
ticofab On

I will add my library for GPX parsing to these answers: https://github.com/ticofab/android-gpx-parser. It provides two ways to parse you GPX file: once you obtain / create a GPXParser object (mParser in the examples below), you can then either parse directly your GPX file

Gpx parsedGpx = null;
try {
    InputStream in = getAssets().open("test.gpx");
    parsedGpx = mParser.parse(in);
} catch (IOException | XmlPullParserException e) {
    e.printStackTrace();
}
if (parsedGpx == null) {
    // error parsing track
} else {
    // do something with the parsed track
}

or you can parse a remote file:

mParser.parse("http://myserver.com/track.gpx", new GpxFetchedAndParsed() {
    @Override
    public void onGpxFetchedAndParsed(Gpx gpx) {
        if (gpx == null) {
            // error parsing track
        } else {
            // do something with the parsed track
        }
    }
});

Contributions are welcome.

4
Urizev On

I've ported the library GPXParser by ghitabot to Android.

https://github.com/urizev/j4gpx