1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
use crate::error::Error;
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use serde::{Serialize, Deserialize};
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
pub struct LatLng {
pub lat: Decimal,
pub lng: Decimal,
}
impl LatLng {
pub fn try_from(latitude: Decimal, longitude: Decimal) -> Result<LatLng, Error> {
if latitude < dec!(-90.0) || latitude > dec!(90.0) {
return Err(Error::InvalidLatitude(latitude, longitude))
}
if longitude < dec!(-180.0) || longitude > dec!(180.0) {
return Err(Error::InvalidLongitude(latitude, longitude))
}
Ok(LatLng {
lat: latitude,
lng: longitude,
})
}
}
impl std::convert::From<&LatLng> for String {
fn from(latlng: &LatLng) -> String {
format!("{},{}", latlng.lat.normalize(), latlng.lng.normalize())
}
}
impl std::default::Default for LatLng {
fn default() -> Self {
LatLng {
lat: dec!(0.0),
lng: dec!(0.0),
}
}
}
impl std::fmt::Display for LatLng {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let ns_hemisphere = if self.lat > dec!(0.0) {
String::from(" N")
} else if self.lat == dec!(0.0) {
String::from("")
} else {
String::from(" S")
};
let ew_hemisphere = if self.lng > dec!(0.0) {
String::from(" E")
} else if self.lng == dec!(0.0) {
String::from("")
} else {
String::from(" W")
};
write!(f,
"{}°{} {}°{}",
self.lat.abs().normalize(), ns_hemisphere,
self.lng.abs().normalize(), ew_hemisphere,
)
}
}