问题是在Android设备上通过http get request(retrofit)下载gpx文件,解析它并在谷歌地图上显示路线。
我首先使用改造并将像“cyclingRoute.gpx”这样的文件保存到设备上的下载文件,如下所示:
NetworkBuilder.getAppNetwork().getRoute(routeId).enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.e("@@@@@@@@@@@", "API SUCCESS");
try {
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File file = new File(path, "cyclingRoute.gpx");
FileOutputStream fileOutputStream = new FileOutputStream(file);
IOUtils.write(response.body().bytes(), fileOutputStream);
parseRoute(file);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("@@@@@@@@@@@", "API FAILS" + t.getMessage());
}
});
对于解析部分,我使用了来自android arsenal的第三方库:https://github.com/ticofab/android-gpx-parser
GPXParser mParser = new GPXParser();
Gpx parsedGpx = null;
try {
InputStream is = getClass().getResourceAsStream(file.getName());
parsedGpx = mParser.parse(is);
} catch (IOException | XmlPullParserException e) {
// do something with this exception
e.printStackTrace();
}
if (parsedGpx == null) {
// error parsing track
} else {
// do something with the parsed track
List<Track> tracks = parsedGpx.getTracks();
for (int i = 0; i < tracks.size(); i++) {
Track track = tracks.get(i);
Log.d(TAG, "track " + i + ":");
List<TrackSegment> segments = track.getTrackSegments();
for (int j = 0; j < segments.size(); j++) {
TrackSegment segment = segments.get(j);
Log.d(TAG, " segment " + j + ":");
for (TrackPoint trackPoint : segment.getTrackPoints()) {
Log.d(TAG, " point: lat " + trackPoint.getLatitude() + ", lon " + trackPoint.getLongitude());
}
}
}
}
当我运行代码“InputStream is”为null并抛出异常。我在哪里做错了?
而不是这一行 - > InputStream is = getClass()。getResourceAsStream(file.getName());
我也试过这个 - > InputStream in = getAssets()。open(“cycylingRoute.gpx”);
并抛出异常,告知没有找到目录或文件。
而且我打算收集json中的所有曲目并将其传递给谷歌地图(如果这是一种正确的方法)。有什么建议吗?
如果你帮助我,我真的很感激!!
谢谢。
在InputStream in = getAssets().open("cycylingRoute.gpx");
,您在哪里定义“下载”?
您正在使用File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
存储文件。