66 lines
1.6 KiB
Rust
66 lines
1.6 KiB
Rust
use std::str::FromStr;
|
|
|
|
use wasm_bindgen::prelude::*;
|
|
use xpin::Address;
|
|
|
|
#[wasm_bindgen]
|
|
pub struct EncodedAddress {
|
|
address: String,
|
|
pub lat: f64,
|
|
pub lon: f64,
|
|
}
|
|
|
|
#[wasm_bindgen]
|
|
impl EncodedAddress {
|
|
/// Get the current address as decimal degrees
|
|
#[wasm_bindgen]
|
|
pub fn get_decimal_degrees(&self) -> String {
|
|
format!("{}, {}", self.lat, self.lon)
|
|
}
|
|
|
|
/// Get an encoded address from a latitude/longitude
|
|
#[wasm_bindgen]
|
|
pub fn from_lat_lon(lat: f64, lon: f64) -> Result<EncodedAddress, String> {
|
|
xpin::Address::from_lat_lon(lat, lon)
|
|
.as_ref()
|
|
.map(EncodedAddress::from)
|
|
.map_err(|e| e.to_string())
|
|
}
|
|
|
|
#[wasm_bindgen]
|
|
pub fn from_address(addr_str: &str) -> Result<EncodedAddress, String> {
|
|
xpin::Address::from_str(addr_str)
|
|
.as_ref()
|
|
.map(EncodedAddress::from)
|
|
.map_err(|e| e.to_string())
|
|
}
|
|
|
|
#[wasm_bindgen]
|
|
pub fn get_address(&self) -> String {
|
|
self.address.clone()
|
|
}
|
|
|
|
#[wasm_bindgen]
|
|
pub fn get_lat_lon(&self) -> Vec<f64> {
|
|
vec![self.lat, self.lon]
|
|
}
|
|
}
|
|
|
|
#[wasm_bindgen]
|
|
pub fn parse(i: &str) -> Result<String, String> {
|
|
spatial_coordinate_systems::Coordinate::from_str(i)
|
|
.map(|c| format!("{c:?}"))
|
|
.map_err(|()| format!("Could not parse str as a coordinate {i:?}"))
|
|
}
|
|
|
|
impl From<&'_ Address<'_>> for EncodedAddress {
|
|
fn from(addr: &Address) -> Self {
|
|
let (lat, lon) = addr.as_lat_lon();
|
|
Self {
|
|
address: addr.to_string(),
|
|
lat,
|
|
lon,
|
|
}
|
|
}
|
|
}
|