geojson-tile-renderer 0.1.0

Convert GeoJSON features to PNG tile images with Web Mercator projection
Documentation
use geojson::Feature;

/// Gets a property value as a string from feature properties
///
/// # Arguments
/// * `feature` - GeoJSON feature
/// * `key` - Property key to retrieve
/// * `default` - Default value if property is missing or not a string
///
/// # Returns
/// Property value as a String, or the default value
pub fn get_property_str(feature: &Feature, key: &str, default: &str) -> String {
	feature
		.properties
		.as_ref()
		.and_then(|props| props.get(key))
		.and_then(|val| val.as_str())
		.unwrap_or(default)
		.to_string()
}

/// Gets a property value as a number from feature properties
///
/// # Arguments
/// * `feature` - GeoJSON feature
/// * `key` - Property key to retrieve
/// * `default` - Default value if property is missing or not a number
///
/// # Returns
/// Property value as f64, or the default value
pub fn get_property_num(feature: &Feature, key: &str, default: f64) -> f64 {
	feature
		.properties
		.as_ref()
		.and_then(|props| props.get(key))
		.and_then(|val| val.as_f64())
		.unwrap_or(default)
}

#[cfg(test)]
mod tests {
	use super::*;
	use serde_json::json;

	#[test]
	fn test_get_property_str_found() {
		let feature: Feature = serde_json::from_value(json!({
			"type": "Feature",
			"geometry": {"type": "Point", "coordinates": [0.0, 0.0]},
			"properties": {
				"name": "test",
				"color": "red"
			}
		}))
		.unwrap();

		assert_eq!(get_property_str(&feature, "name", "default"), "test");
		assert_eq!(get_property_str(&feature, "color", "default"), "red");
	}

	#[test]
	fn test_get_property_str_missing() {
		let feature: Feature = serde_json::from_value(json!({
			"type": "Feature",
			"geometry": {"type": "Point", "coordinates": [0.0, 0.0]},
			"properties": {}
		}))
		.unwrap();

		assert_eq!(get_property_str(&feature, "name", "default"), "default");
	}

	#[test]
	fn test_get_property_num_found() {
		let feature: Feature = serde_json::from_value(json!({
			"type": "Feature",
			"geometry": {"type": "Point", "coordinates": [0.0, 0.0]},
			"properties": {
				"size": 42,
				"opacity": 0.5
			}
		}))
		.unwrap();

		assert_eq!(get_property_num(&feature, "size", 10.0), 42.0);
		assert_eq!(get_property_num(&feature, "opacity", 1.0), 0.5);
	}

	#[test]
	fn test_get_property_num_missing() {
		let feature: Feature = serde_json::from_value(json!({
			"type": "Feature",
			"geometry": {"type": "Point", "coordinates": [0.0, 0.0]},
			"properties": {}
		}))
		.unwrap();

		assert_eq!(get_property_num(&feature, "size", 10.0), 10.0);
	}
}