6 releases (breaking)
0.5.1 | Jun 25, 2022 |
---|---|
0.5.0 | Feb 4, 2021 |
0.4.0 | Dec 30, 2020 |
0.3.0 | Oct 22, 2020 |
0.1.0 | Nov 19, 2018 |
#1713 in Parser implementations
734 downloads per month
Used in 2 crates
255KB
1.5K
SLoC
rust-topojson
TopoJSON utilities for Rust
Licensed under the MIT license.
lib.rs
:
Examples
This crate uses serde
for serialization and allows conversion to GeoJson objects.
To get started, add topojson
to your Cargo.toml
:
[dependencies]
topojson = "*"
Reading
use topojson::TopoJson;
let topojson_str = r#"
{
"arcs": [[[0.0, 0.0], [0.0, 9999.0], [2000.0, 0.0], [0.0, -9999.0], [-2000.0, 0.0]]],
"objects": {"example ": {
"type": "GeometryCollection",
"geometries": [
{"coordinates": [4000.0, 5000.0],
"properties": {"prop0": "value0"},
"type": "Point"},
{"arcs": [[0]],
"properties": {"prop0": "value0", "prop1": {"this": "that"}},
"type": "Polygon"}
]
}},
"transform": {"scale": [0.0005, 0.0001], "translate": [100.0, 0.0]},
"type": "Topology"
}
"#;
let topo = topojson_str.parse::<TopoJson>().unwrap();
Writing
TopoJson
can then be serialized by calling to_string
:
use topojson::{TopoJson, Geometry, Value, Topology, NamedGeometry};
use serde_json;
let topo = Topology {
arcs: vec![
vec![vec![2.2, 2.2], vec![3.3, 3.3]]
],
objects: vec![NamedGeometry {
name: String::from("example"),
geometry: Geometry {
value: Value::LineString(vec![0]),
bbox: None,
id: None,
properties: None,
foreign_members: None,
},
}],
bbox: None,
transform: None,
foreign_members: None,
};
let topojson_string = serde_json::to_string(&topo).unwrap();
Converting to GeoJson
TopoJson
can then be converted to GeoJson using the
to_geojson` function:
extern crate geojson;
use topojson::{TopoJson, to_geojson};
use geojson::GeoJson;
let topojson_str = r#"
{
"arcs": [[[0.0, 0.0], [0.0, 9999.0], [2000.0, 0.0], [0.0, -9999.0], [-2000.0, 0.0]]],
"objects": {"example": { "type": "GeometryCollection", "geometries": [
{"coordinates": [4000.0, 5000.0], "properties": {"prop0": "value0"}, "type": "Point"},
{"arcs": [[0]], "properties": {"prop0": "value0", "prop1": {"this": "that"}}, "type": "Polygon"}]}},
"transform": {"scale": [0.0005, 0.0001], "translate": [100.0, 0.0]},
"type": "Topology"
}"#;
// Parse to Topology:
let topo = topojson_str.parse::<TopoJson>().unwrap();
// Conversion to GeoJson FeatureCollection for the "example" object:
let geojson = match topo {
TopoJson::Topology(t) => {
to_geojson(&t, &String::from("example"))
.expect("Unable to convert TopoJSON to GeoJSON")
},
_ => unimplemented!(),
};
Dependencies
~1.6–2.6MB
~54K SLoC