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 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
//! Contains the `LatLng` struct, its associated traits, and functions. The
//! latitude & longitude coorindate system is used to specify a position or
//! location on the Earth's surface.
#[cfg(feature = "geo")]
mod geo;
// -----------------------------------------------------------------------------
use crate::error::Error as GoogleMapsError;
use crate::types::error::Error as TypeError;
use rust_decimal::prelude::FromPrimitive;
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use serde::{Deserialize, Serialize};
use std::cmp::{Ord, Ordering};
// -----------------------------------------------------------------------------
/// Latitude and longitude values must correspond to a valid location on the
/// face of the earth. Latitudes can take any value between -90 and 90 while
/// longitude values can take any value between -180 and 180. If you specify an
/// invalid latitude or longitude value, your request will be rejected as a bad
/// request.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
pub struct LatLng {
/// Latitude. A value between -90.0° and 90.0°.
#[serde(alias = "y")]
#[serde(alias = "lat")]
#[serde(alias = "latitude")]
pub lat: Decimal,
/// Longitude. A value between -180.0° and 180.0°.
#[serde(alias = "x")]
#[serde(alias = "lon")]
#[serde(alias = "long")]
#[serde(alias = "longitude")]
pub lng: Decimal,
} // struct
// -----------------------------------------------------------------------------
impl LatLng {
/// Takes individual latitude & longitude `Decimal` coordinates and
/// converts them into a `LatLng` structure. If either the latitude
/// (-90.0 to +90.0) or longitude (-180.0 to +180.0) are out of range, this
/// function will return an error.
pub fn try_from_dec(latitude: Decimal, longitude: Decimal) -> Result<Self, GoogleMapsError> {
if latitude < dec!(-90.0) || latitude > dec!(90.0) {
Err(TypeError::InvalidLatitude(latitude, longitude))?;
} // if
if longitude < dec!(-180.0) || longitude > dec!(180.0) {
Err(TypeError::InvalidLongitude(latitude, longitude))?;
} // if
Ok(Self {
lat: latitude,
lng: longitude,
})
} // fn
} // impl
// -----------------------------------------------------------------------------
impl LatLng {
/// Takes individual latitude & longitude `f32` coordinates and
/// converts them into a `LatLng` structure. If either the latitude
/// (-90.0 to +90.0) or longitude (-180.0 to +180.0) are out of range, this
/// function will return an error.
pub fn try_from_f32(latitude: f32, longitude: f32) -> Result<Self, GoogleMapsError> {
let lat: Decimal = Decimal::from_f32(latitude)
.ok_or_else(|| TypeError::FloatToDecimalConversionError(latitude.to_string()))?;
let lng: Decimal = Decimal::from_f32(longitude)
.ok_or_else(|| TypeError::FloatToDecimalConversionError(longitude.to_string()))?;
if lat < dec!(-90.0) || lat > dec!(90.0) {
Err(TypeError::InvalidLatitude(lat, lng))?;
} // if
if lng < dec!(-180.0) || lng > dec!(180.0) {
Err(TypeError::InvalidLongitude(lat, lng))?;
} // if
Ok(Self { lat, lng })
} // fn
} // impl
// -----------------------------------------------------------------------------
impl LatLng {
/// Takes individual latitude & longitude `f64` coordinates and
/// converts them into a `LatLng` structure. If either the latitude
/// (-90.0 to +90.0) or longitude (-180.0 to +180.0) are out of range, this
/// function will return an error.
pub fn try_from_f64(latitude: f64, longitude: f64) -> Result<Self, GoogleMapsError> {
let lat: Decimal = Decimal::from_f64(latitude)
.ok_or_else(|| TypeError::FloatToDecimalConversionError(latitude.to_string()))?;
let lng: Decimal = Decimal::from_f64(longitude)
.ok_or_else(|| TypeError::FloatToDecimalConversionError(longitude.to_string()))?;
if lat < dec!(-90.0) || lat > dec!(90.0) {
Err(TypeError::InvalidLatitude(lat, lng))?;
} // if
if lng < dec!(-180.0) || lng > dec!(180.0) {
Err(TypeError::InvalidLongitude(lat, lng))?;
} // if
Ok(Self { lat, lng })
} // fn
} // impl
// -----------------------------------------------------------------------------
impl std::str::FromStr for LatLng {
// Error definitions are contained in the
// `google_maps\src\geocoding\error.rs` module.
type Err = GoogleMapsError;
/// Attempts to get a `LatLng` struct from a borrowed `&str` that contains a
/// comma-delimited latitude & longitude pair.
fn from_str(str: &str) -> Result<Self, Self::Err> {
let coordinates: Vec<&str> = str.trim().split(',').collect();
if coordinates.len() == 2 {
let lat = Decimal::from_str(coordinates[0].trim());
let lat = lat.map_err(|_| TypeError::InvalidLatLongString(str.to_owned()))?;
let lon = Decimal::from_str(coordinates[1].trim());
let lon = lon.map_err(|_| TypeError::InvalidLatLongString(str.to_owned()))?;
Self::try_from_dec(lat, lon)
} else {
Err(TypeError::InvalidLatLongString(str.to_owned()))?
} // if
} // fn
} // impl
// -----------------------------------------------------------------------------
impl TryFrom<&str> for LatLng {
type Error = GoogleMapsError;
/// Attempts to get a `LatLng` struct from a borrowed `&str` that contains a
/// comma-delimited latitude & longitude pair.
fn try_from(str: &str) -> Result<Self, Self::Error> {
str.parse()
}
} // impl
// -----------------------------------------------------------------------------
impl TryFrom<&String> for LatLng {
type Error = GoogleMapsError;
/// Attempts to get a `LatLng` struct from a borrowed `&String` that
/// contains a comma-delimited latitude & longitude pair.
fn try_from(string: &String) -> Result<Self, Self::Error> {
string.parse()
}
} // impl
// -----------------------------------------------------------------------------
impl TryFrom<String> for LatLng {
type Error = GoogleMapsError;
/// Attempts to get a `LatLng` struct from an owned `String` that contains a
/// comma-delimited latitude & longitude pair.
fn try_from(string: String) -> Result<Self, Self::Error> {
string.parse()
}
} // impl
// -----------------------------------------------------------------------------
impl std::convert::From<&LatLng> for String {
/// Converts a borrowed `&LatLng` struct to a `String` that contains a
/// latitude/longitude pair.
fn from(lat_lng: &LatLng) -> Self {
format!(
"{latitude},{longitude}",
latitude = lat_lng.lat.normalize(),
longitude = lat_lng.lng.normalize(),
) // format!
} // fn
} // impl
// -----------------------------------------------------------------------------
impl std::convert::From<LatLng> for String {
/// Converts an owned `LatLng` struct to a `String` that contains a
/// latitude/longitude pair.
fn from(lat_lng: LatLng) -> Self {
Self::from(&lat_lng)
}
} // impl
// -----------------------------------------------------------------------------
impl std::fmt::Display for LatLng {
/// Converts a `LatLng` struct to a string that contains a
/// latitude/longitude pair.
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", String::from(self))
} // fn
} // impl
// -----------------------------------------------------------------------------
impl std::default::Default for LatLng {
/// Returns a reasonable default value for the `LatLng` struct.
fn default() -> Self {
Self {
lat: dec!(0.0),
lng: dec!(0.0),
}
} // fn
} // impl
// -----------------------------------------------------------------------------
impl LatLng {
/// Formats a `LatLng` struct into a string that is presentable to the end
/// user.
#[must_use]
pub fn display(&self) -> String {
// Display latitude and longitude as decimal degrees with some extra
// fixins'.
format!(
"{lat}°{lat_hem} {lng}°{lng_hem}",
lat = self.lat.abs().normalize(),
lat_hem = match self.lat.cmp(&dec!(0.0)) {
Ordering::Less => " S".to_string(),
Ordering::Greater => " N".to_string(),
Ordering::Equal => String::new(),
}, // match
lng = self.lng.abs().normalize(),
lng_hem = match self.lng.cmp(&dec!(0.0)) {
Ordering::Less => " W".to_string(),
Ordering::Greater => " E".to_string(),
Ordering::Equal => String::new(),
}, // match
) // write!
} // fn
} // impl
// -----------------------------------------------------------------------------
impl LatLng {
/// Returns the north-south latitudinal (or vertical) coordinate.
#[must_use]
pub const fn y(&self) -> &Decimal {
&self.lat
}
/// Returns the north-south latitudinal (or vertical) coordinate.
#[must_use]
pub const fn lat(&self) -> &Decimal {
&self.lat
}
/// Returns the north-south latitudinal (or vertical) coordinate.
#[must_use]
pub const fn latitude(&self) -> &Decimal {
&self.lat
}
/// Returns the east-west longitudinal (or horizontal) coordinate.
#[must_use]
pub const fn x(&self) -> &Decimal {
&self.lng
}
/// Returns the east-west longitudinal (or horizontal) coordinate.
#[must_use]
pub const fn lng(&self) -> &Decimal {
&self.lng
}
/// Returns the east-west longitudinal (or horizontal) coordinate.
#[must_use]
pub const fn lon(&self) -> &Decimal {
&self.lng
}
/// Returns the east-west longitudinal (or horizontal) coordinate.
#[must_use]
pub const fn long(&self) -> &Decimal {
&self.lng
}
/// Returns the east-west longitudinal (or horizontal) coordinate.
#[must_use]
pub const fn longitude(&self) -> &Decimal {
&self.lng
}
/// Returns a tuple containing 1. the latitude (y) coordinate, and then 2.
/// the longitude (x) coordinate, in that order.
#[must_use]
pub const fn coords(&self) -> (&Decimal, &Decimal) {
(&self.lat, &self.lng)
}
/// Returns a tuple containing 1. the latitude (y) coordinate, and then 2.
/// the longitude (x) coordinate, in that order.
#[must_use]
pub const fn coordinates(&self) -> (&Decimal, &Decimal) {
(&self.lat, &self.lng)
}
} // impl