18 个版本 (10 个破坏性版本)
0.10.0 | 2023 年 12 月 4 日 |
---|---|
0.9.1 | 2023 年 6 月 5 日 |
0.9.0 | 2023 年 5 月 30 日 |
0.8.6 | 2022 年 5 月 28 日 |
0.0.1 | 2015 年 1 月 21 日 |
#223 在 解析器实现
5,261 每月下载量
用于 12 crates
140KB
2.5K SLoC
gpx
gpx 是一个用于读取和写入 GPX (GPS Exchange Format) 文件的库。它使用 geo-types 提供的原语来允许存储 GPS 数据。
示例
读取 GPX 文件
extern crate gpx;
use std::io::BufReader;
use std::fs::File;
use gpx::read;
use gpx::{Gpx, Track, TrackSegment};
fn main() {
// This XML file actually exists — try it for yourself!
let file = File::open("tests/fixtures/wikipedia_example.gpx").unwrap();
let reader = BufReader::new(file);
// read takes any io::Read and gives a Result<Gpx, Error>.
let gpx: Gpx = read(reader).unwrap();
// Each GPX file has multiple "tracks", this takes the first one.
let track: &Track = &gpx.tracks[0];
assert_eq!(track.name, Some(String::from("Example GPX Document")));
// Each track will have different segments full of waypoints, where a
// waypoint contains info like latitude, longitude, and elevation.
let segment: &TrackSegment = &track.segments[0];
// This is an example of retrieving the elevation (in meters) at certain points.
assert_eq!(segment.points[0].elevation, Some(4.46));
assert_eq!(segment.points[1].elevation, Some(4.94));
assert_eq!(segment.points[2].elevation, Some(6.87));
}
生成新的 GPX 文件
此示例仅生成轨迹。您还可以通过实例化新的 Waypoint
和 Route
来添加航点和路线。
use geo_types::{coord, Point};
use gpx::{Gpx, GpxVersion, Track, TrackSegment, Waypoint};
use std::{error::Error, fs::File, io::BufWriter, path::Path};
pub fn to_gpx<P: AsRef<Path>>(out_path: P) -> Result<(), Box<dyn Error>> {
// Instantiate Gpx struct
let track_segment = TrackSegment {
points: vec![]
};
let track = Track {
name: Some("Track 1".to_string()),
comment: None,
description: None,
source: None,
links: vec![],
type_: None,
number: None,
segments: vec![track_segment],
};
let mut gpx = Gpx {
version: GpxVersion::Gpx11,
creator: None,
metadata: None,
waypoints: vec![],
tracks: vec![track],
routes: vec![],
};
// Create file at path
let gpx_file = File::create(out_path)?;
let buf = BufWriter::new(gpx_file);
// Add track point
let geo_coord = coord! { x: -121.1, y: 38.82 };
let geo_point: Point = geo_coord.into();
gpx.tracks[0].segments[0].points.push(Waypoint::new(geo_point));
// Write to file
gpx::write(&gpx, buf)?;
Ok(())
}
写入字符串
write
将 GPX 输出写入实现 std::io::Write
的任何内容。要将输出保存到字符串,请将其写入 u8
向量,然后将向量转换为字符串。
let mut vec = Vec::new();
gpx::write(&gpx, &mut vec)?;
let string = String::from_utf8(vec)?;
当前状态
rust-gpx 当前支持读取和写入 GPX 1.1 和 1.0。尚不支持 GPX 扩展。
贡献
欢迎所有贡献!如果您发现错误或有任何疑问,请提交问题,并始终欢迎拉取请求。
许可证
rust-gpx 在 MIT 许可证 下授权。
依赖项
~1.8–2.5MB
~51K SLoC