gpxjson.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. #include <iostream>
  2. #include <cstring>
  3. #include <fstream>
  4. #include <vector>
  5. #include <cmath>
  6. #include <limits>
  7. #include <iomanip>
  8. #include "XMLParser.h"
  9. #include "Arguments.h"
  10. #include "Algorithm.h"
  11. // ----------------------------------------------------------------------------
  12. namespace gpxtools
  13. {
  14. class GPXJson : public XMLParserHandler
  15. {
  16. private:
  17. const std::string LATLON = "latlon";
  18. const std::string LONLAT = "lonlat";
  19. public:
  20. // -- Constructor -----------------------------------------------------------
  21. GPXJson() :
  22. _arguments("gpxjson [OPTION].. [FILE]\nDisplay the GeoJson data from a GPX-file on standard output.\n", "gpxjson v0.1", "Display the waypoints, routes and/or tracks in GeoJson format from a GPX-file on standard output."),
  23. _waypoints (_arguments, true, 'w', "waypoints", "convert the waypoints"),
  24. _tracks (_arguments, true, 't', "tracks", "convert the tracks"),
  25. _routes (_arguments, true, 'r', "routes", "convert the routes"),
  26. _format (_arguments, true, 'f', "format", "geojson|plain", "set the output format (def:geojson)", "geojson"),
  27. _mode (_arguments, true, 'm', "mode", "compact|normal", "set the output mode (def:normal)", "normal"),
  28. _coordinates(_arguments, true, 'c', "coordinates", "lonlat|latlon", "set the type of coordinates for plain format (def:lonlat)", LONLAT),
  29. _number (_arguments, true, 'p', "points", "NUMBER", "set the number of points per line in normal mode (def:4)", "4"),
  30. _simplify (_arguments, true, 's', "simplify", "METRES", "simplify the route by track distance", ""),
  31. _xmlParser (this)
  32. {
  33. }
  34. // -- Deconstructor ---------------------------------------------------------
  35. virtual ~GPXJson()
  36. {
  37. }
  38. // -- Properties ------------------------------------------------------------
  39. // -- Parse arguments -------------------------------------------------------
  40. bool parseArguments(int argc, char *argv[])
  41. {
  42. std::vector<std::string> filenames;
  43. if (!_arguments.parse(argc,argv, filenames))
  44. {
  45. return false;
  46. }
  47. else if (!checkArguments(filenames))
  48. {
  49. return false;
  50. }
  51. else if (filenames.empty())
  52. {
  53. return _xmlParser.parse(std::cin);
  54. }
  55. else
  56. {
  57. return parseFile(filenames.front());
  58. }
  59. }
  60. // -- Check arguments -------------------------------------------------------
  61. bool checkArguments(const std::vector<std::string> &filenames)
  62. {
  63. if (filenames.size() > 1)
  64. {
  65. std::cerr << "Too many input files." << std::endl;
  66. return false;
  67. }
  68. if ((_format.value() != "geojson") && (_format.value() != "plain"))
  69. {
  70. std::cerr << "Invalid value for --" << _format.longOption() << ": " << _format.value() << std::endl;
  71. return false;
  72. }
  73. if ((_mode.value() != "compact") && (_mode.value() != "normal"))
  74. {
  75. std::cerr << "Invalid value for --" << _mode.longOption() << ": " << _mode.value() << std::endl;
  76. return false;
  77. }
  78. if ((_coordinates.value() != LATLON) && (_coordinates.value() != LONLAT))
  79. {
  80. std::cerr << "Invalid value for --" << _mode.longOption() << ": " << _mode.value() << std::endl;
  81. return false;
  82. }
  83. try
  84. {
  85. int number = std::stoi(_number.value());
  86. if (number <= 0)
  87. {
  88. std::cerr << "Invalid value for --" << _number.longOption() << ": " << _number.value() << std::endl;
  89. return false;
  90. }
  91. }
  92. catch (...)
  93. {
  94. std::cerr << "Invalid number for --" << _number.longOption() << ": " << _number.value() << std::endl;
  95. return false;
  96. }
  97. if (_simplify.active())
  98. {
  99. try
  100. {
  101. double distance = std::stod(_simplify.value());
  102. if (distance <= 0.0)
  103. {
  104. std::cerr << "Invalid value for --" << _number.longOption() << ": " << _simplify.value() << std::endl;
  105. return false;
  106. }
  107. }
  108. catch(...)
  109. {
  110. std::cerr << "Invalid value for --" << _number.longOption() << ": " << _simplify.value() << std::endl;
  111. return false;
  112. }
  113. }
  114. return true;
  115. }
  116. // -- Parse a file ----------------------------------------------------------
  117. bool parseFile(const std::string &filename)
  118. {
  119. bool ok =false;
  120. std::ifstream file(filename);
  121. if (file.is_open())
  122. {
  123. ok = _xmlParser.parse(file);
  124. file.close();
  125. }
  126. else
  127. {
  128. std::cerr << "Unable to open: " << filename << std::endl;
  129. }
  130. return ok;
  131. }
  132. void outputJson(std::ostream &output)
  133. {
  134. std::size_t points = _points.size();
  135. std::size_t lines = _lines.size();
  136. if (_format.value() == "geojson")
  137. {
  138. if (points == 1) outputSingleGeoJsonPoint(output);
  139. if (points > 1) outputMultipleGeoJsonPoints(output);
  140. if (lines == 1) outputSingleGeoJsonLine(output);
  141. if (lines > 1) outputMultipleGeoJsonLines(output);
  142. }
  143. else if (_format.value() == "plain")
  144. {
  145. if (points == 1) outputSinglePlainPoint(output);
  146. if (points > 1) outputMultiplePlainPoints(output);
  147. if (lines == 1) outputSinglePlainLine(output);
  148. if (lines > 1) outputMultiplePlainLines(output);
  149. }
  150. }
  151. void simplify()
  152. {
  153. if (!_simplify.active()) return;
  154. double setting = std::stod(_simplify.value());
  155. for (auto line = _lines.begin(); line != _lines.end(); ++line)
  156. {
  157. while (true)
  158. {
  159. auto p1 = line->end();
  160. auto p2 = line->end();
  161. auto p3 = line->begin();
  162. auto ps = line->end();
  163. double low = 9999.99;
  164. while (p3 != line->end())
  165. {
  166. if ((p1 != line->end()) && (p2 != line->end()))
  167. {
  168. double d = (gpx::calcDistance(p1->_lat, p1->_lon, p2->_lat, p2->_lon) +
  169. gpx::calcDistance(p2->_lat, p2->_lon, p3->_lat, p3->_lon)) -
  170. gpx::calcDistance(p1->_lat, p1->_lon, p3->_lat, p3->_lon);
  171. if (d < low)
  172. {
  173. low = d;
  174. ps = p2;
  175. }
  176. }
  177. p1 = p2;
  178. p2 = p3;
  179. ++p3;
  180. }
  181. if ((low > setting) || (ps == line->end())) break;
  182. line->erase(ps);
  183. }
  184. }
  185. }
  186. private:
  187. void outputSingleGeoJsonPoint(std::ostream &output)
  188. {
  189. output << std::fixed << std::setprecision(6);
  190. output << '{'; doEndl(output);
  191. doIndent();
  192. output << _indent << "\"type\":\"Point\","; doEndl(output);
  193. output << _indent << "\"coordinates\":[" << _points.front()._lon << ',' << _points.front()._lat << "]"; doEndl(output);
  194. doOutdent();
  195. output << '}'; doEndl(output);
  196. }
  197. void outputMultipleGeoJsonPoints(std::ostream &output)
  198. {
  199. output << std::fixed << std::setprecision(6);
  200. output << '{'; doEndl(output);
  201. doIndent();
  202. output << _indent << "\"type\":\"MultiPoint\","; doEndl(output);
  203. output << _indent << "\"coordinates\":["; doEndl(output);
  204. doIndent();
  205. int number = std::stoi(_number.value());
  206. auto iter = _points.begin();
  207. while (iter != _points.end())
  208. {
  209. output << _indent;
  210. int count = 0;
  211. while (iter != _points.end() && count < number)
  212. {
  213. auto next = iter + 1;
  214. output << '[' << iter->_lon << ',' << iter->_lat << ']';
  215. if (next != _points.end()) output << ',';
  216. ++iter; count++;
  217. }
  218. doEndl(output);
  219. }
  220. doOutdent();
  221. output << _indent << "]"; doEndl(output);
  222. doOutdent();
  223. output << '}'; doEndl(output);
  224. }
  225. void outputSingleGeoJsonLine(std::ostream &output)
  226. {
  227. output << std::fixed << std::setprecision(6);
  228. output << '{'; doEndl(output);
  229. doIndent();
  230. output << _indent << "\"type\":\"LineString\","; doEndl(output);
  231. output << _indent << "\"coordinates\":["; doEndl(output);
  232. doIndent();
  233. int number = std::stoi(_number.value());
  234. auto iter = _lines.front().begin();
  235. auto end = _lines.front().end();
  236. while (iter != end)
  237. {
  238. output << _indent;
  239. int count = 0;
  240. while (iter != end && count < number)
  241. {
  242. auto next = iter + 1;
  243. output << '[' << iter->_lon << ',' << iter->_lat << ']';
  244. if (next != end) output << ',';
  245. ++iter; count++;
  246. }
  247. doEndl(output);
  248. }
  249. doOutdent();
  250. output << _indent << "]"; doEndl(output);
  251. doOutdent();
  252. output << '}'; doEndl(output);
  253. }
  254. void outputMultipleGeoJsonLines(std::ostream &output)
  255. {
  256. output << std::fixed << std::setprecision(6);
  257. output << '{'; doEndl(output);
  258. doIndent();
  259. output << _indent << "\"type\":\"MultiLineString\","; doEndl(output);
  260. output << _indent << "\"coordinates\":["; doEndl(output);
  261. doIndent();
  262. int number = std::stoi(_number.value());
  263. output << _indent;
  264. for (auto iter2 = _lines.begin(); iter2 != _lines.end(); ++iter2)
  265. {
  266. auto next2 = iter2 + 1;
  267. output << "["; doEndl(output);
  268. doIndent();
  269. auto iter = iter2->begin();
  270. while (iter != iter2->end())
  271. {
  272. output << _indent;
  273. int count = 0;
  274. while (iter != iter2->end() && count < number)
  275. {
  276. auto next = iter + 1;
  277. output << '[' << iter->_lon << ',' << iter->_lat << ']';
  278. if (next != iter2->end()) output << ',';
  279. ++iter; count++;
  280. }
  281. doEndl(output);
  282. }
  283. doOutdent();
  284. output << _indent << "]";
  285. if (next2 != _lines.end()) output << ",";
  286. }
  287. doEndl(output);
  288. doOutdent();
  289. output << _indent << "]"; doEndl(output);
  290. doOutdent();
  291. output << "}"; doEndl(output);
  292. }
  293. void outputSinglePlainPoint(std::ostream &output)
  294. {
  295. output << std::fixed << std::setprecision(6);
  296. if (_coordinates.value() == LONLAT)
  297. {
  298. output << '[' << _points.front()._lon << ',' << _points.front()._lat << ']';
  299. }
  300. else
  301. {
  302. output << '[' << _points.front()._lat << ',' << _points.front()._lon << ']';
  303. }
  304. doEndl(output);
  305. }
  306. void outputMultiplePlainPoints(std::ostream &output)
  307. {
  308. const int columns = std::stoi(_number.value());
  309. const bool lonlat = (_coordinates.value() == LONLAT);
  310. output << std::fixed << std::setprecision(6);
  311. output << '['; doEndl(output);
  312. doIndent();
  313. auto point = _points.begin();
  314. while (point != _points.end())
  315. {
  316. output << _indent;
  317. int column = 0;
  318. while ((point != _points.end()) && (column < columns))
  319. {
  320. if (lonlat)
  321. {
  322. output << '[' << point->_lon << ',' << point->_lat << ']';
  323. }
  324. else
  325. {
  326. output << '[' << point->_lat << ',' << point->_lon << ']';
  327. }
  328. if ((point + 1) != _points.end()) output << ',';
  329. ++point; column++;
  330. }
  331. doEndl(output);
  332. }
  333. doOutdent();
  334. output << ']'; doEndl(output);
  335. }
  336. void outputSinglePlainLine(std::ostream &output)
  337. {
  338. const int columns = std::stoi(_number.value());
  339. const bool lonlat = (_coordinates.value() == LONLAT);
  340. output << std::fixed << std::setprecision(6);
  341. output << '['; doEndl(output);
  342. doIndent();
  343. auto point = _lines.front().begin();
  344. auto end = _lines.front().end();
  345. while (point != end)
  346. {
  347. output << _indent;
  348. int column = 0;
  349. while ((point != end) && (column < columns))
  350. {
  351. if (lonlat)
  352. {
  353. output << '[' << point->_lon << ',' << point->_lat << ']';
  354. }
  355. else
  356. {
  357. output << '[' << point->_lat << ',' << point->_lon << ']';
  358. }
  359. if ((point + 1) != end) output << ',';
  360. ++point; column++;
  361. }
  362. doEndl(output);
  363. }
  364. doOutdent();
  365. output << ']'; doEndl(output);
  366. }
  367. void outputMultiplePlainLines(std::ostream &output)
  368. {
  369. const int columns = std::stoi(_number.value());
  370. const bool lonlat = (_coordinates.value() == LONLAT);
  371. output << std::fixed << std::setprecision(6);
  372. output << '['; doEndl(output);
  373. doIndent();
  374. for (auto line = _lines.begin(); line != _lines.end(); ++line)
  375. {
  376. output << _indent << '['; doEndl(output);
  377. doIndent();
  378. auto point = line->begin();
  379. auto end = line->end();
  380. while (point != end)
  381. {
  382. output << _indent;
  383. int column = 0;
  384. while ((point != end) && (column < columns))
  385. {
  386. if (lonlat)
  387. {
  388. output << '[' << point->_lon << ',' << point->_lat << ']';
  389. }
  390. else
  391. {
  392. output << '[' << point->_lat << ',' << point->_lon << ']';
  393. }
  394. if ((point + 1) != end) output << ',';
  395. ++point; column++;
  396. }
  397. doEndl(output);
  398. }
  399. doOutdent();
  400. output << _indent << ']';
  401. if ((line + 1) != _lines.end()) output << ',';
  402. doEndl(output);
  403. }
  404. doOutdent();
  405. output << ']'; doEndl(output);
  406. }
  407. void doEndl(std::ostream &output)
  408. {
  409. if (_mode.value() == "normal") output << std::endl;
  410. }
  411. void doIndent()
  412. {
  413. if (_mode.value() == "normal") _indent += " ";
  414. }
  415. void doOutdent()
  416. {
  417. if (_mode.value() == "normal") _indent.erase(_indent.size()-2);
  418. }
  419. static double getDoubleAttribute(const Attributes &atts, const std::string &key)
  420. {
  421. auto iter = atts.find(key);
  422. try
  423. {
  424. return iter != atts.end() ? std::stod(iter->second) : std::numeric_limits<double>::min();
  425. }
  426. catch(...)
  427. {
  428. return std::numeric_limits<double>::min();
  429. }
  430. }
  431. public:
  432. // -- Callbacks -------------------------------------------------------------
  433. virtual void startElement(const std::string &path, const std::string &, const Attributes &attributes)
  434. {
  435. if ((_tracks.active() && (path == "/gpx/trk/trkseg")) ||
  436. (_routes.active() && (path == "/gpx/rte")))
  437. {
  438. _line.clear();
  439. }
  440. else if ((_tracks.active() && (path == "/gpx/trk/trkseg/trkpt")) ||
  441. (_routes.active() && (path == "/gpx/rte/rtept")))
  442. {
  443. double lat = getDoubleAttribute(attributes, "lat");
  444. double lon = getDoubleAttribute(attributes, "lon");
  445. _line.push_back(Point(lat, lon));
  446. }
  447. else if (_waypoints.active() && (path == "/gpx/wpt"))
  448. {
  449. double lat = getDoubleAttribute(attributes, "lat");
  450. double lon = getDoubleAttribute(attributes, "lon");
  451. _points.push_back(Point(lat, lon));
  452. }
  453. }
  454. virtual void text(const std::string &, const std::string &)
  455. {
  456. }
  457. virtual void endElement(const std::string &path, const std::string &)
  458. {
  459. if ((_tracks.active() && (path == "/gpx/trk/trkseg")) ||
  460. (_routes.active() && (path == "/gpx/rte")))
  461. {
  462. _lines.push_back(_line);
  463. }
  464. }
  465. private:
  466. arg::Arguments _arguments;
  467. arg::Argument _waypoints;
  468. arg::Argument _tracks;
  469. arg::Argument _routes;
  470. arg::Argument _format;
  471. arg::Argument _mode;
  472. arg::Argument _coordinates;
  473. arg::Argument _number;
  474. arg::Argument _simplify;
  475. XMLParser _xmlParser;
  476. // Types
  477. struct Point
  478. {
  479. Point(double lat, double lon)
  480. {
  481. _lat = lat;
  482. _lon = lon;
  483. }
  484. double _lat;
  485. double _lon;
  486. };
  487. typedef std::vector<Point> Line;
  488. // Members
  489. Line _line;
  490. std::vector<Line> _lines;
  491. std::vector<Point> _points;
  492. std::string _indent;
  493. };
  494. }
  495. // -- Main program ------------------------------------------------------------
  496. int main(int argc, char *argv[])
  497. {
  498. gpxtools::GPXJson gpxJson;
  499. if (gpxJson.parseArguments(argc, argv))
  500. {
  501. gpxJson.simplify();
  502. gpxJson.outputJson(std::cout);
  503. return 0;
  504. }
  505. return 1;
  506. }