Function to_feature

Source
pub fn to_feature<T>(value: T) -> Result<Feature>
where T: Serialize,
Expand description

Convert a T into a Feature.

This is analogous to serde_json::to_value

Note that if (and only if) T has a field named geometry, it will be serialized to feature.geometry.

All other fields will be serialized to feature.properties.

§Examples

use serde::Serialize;
use geojson::{Feature, Value, Geometry};
use geojson::ser::{to_feature, serialize_geometry};

#[derive(Serialize)]
struct MyStruct {
    // Serialize `geometry` as geojson, rather than using the type's default serialization
    #[serde(serialize_with = "serialize_geometry")]
    geometry: geo_types::Point,
    name: String,
}

let my_struct = MyStruct {
    geometry: geo_types::Point::new(1.0, 2.0),
    name: "My Name".to_string()
};

let feature: Feature = to_feature(my_struct).unwrap();
assert_eq!("My Name", feature.properties.unwrap()["name"]);
assert_eq!(feature.geometry.unwrap(), Geometry::new(Value::Point(vec![1.0, 2.0])));

§Errors

Serialization can fail if T’s implementation of Serialize decides to fail, or if T contains a map with non-string keys.