Skip to main content

france_api_adresse/
reverse.rs

1#[cfg(feature = "blocking")]
2use crate::types::{AddressResult, Error};
3use crate::{client::BAN, types::FilterType};
4
5/// Represents a reverse geocode query.
6#[derive(Debug, Clone)]
7pub struct ReverseQuery {
8    client: BAN,
9
10    lat: f64,
11    lon: f64,
12
13    postcode: Option<String>,
14    city: Option<String>,
15    ty: Option<FilterType>,
16
17    limit: Option<usize>,
18}
19
20impl ReverseQuery {
21    pub(crate) fn new(client: BAN, lat: f64, lon: f64) -> Self {
22        Self {
23            client,
24            lat,
25            lon,
26
27            postcode: None,
28            city: None,
29
30            ty: None,
31
32            limit: None,
33        }
34    }
35
36    /// Filter results by postal code
37    pub fn postcode(mut self, code: impl Into<String>) -> Self {
38        self.postcode = Some(code.into());
39        self
40    }
41    /// Filter results by city
42    pub fn city(mut self, name: impl Into<String>) -> Self {
43        self.city = Some(name.into());
44        self
45    }
46
47    /// Filter results by type, e.g. "housenumber", "street", etc.
48    pub fn filter_type(mut self, ty: FilterType) -> Self {
49        self.ty = Some(ty);
50        self
51    }
52
53    /// Limit number of results returned
54    pub fn limit_results(mut self, limit: usize) -> Self {
55        self.limit = Some(limit);
56        self
57    }
58
59    fn to_url(&self) -> String {
60        let mut url = format!(
61            "{}/reverse/?lat={}&lon={}",
62            self.client.base_url, self.lat, self.lon
63        );
64
65        if let Some(postcode) = &self.postcode {
66            url.push_str(&format!("&postcode={}", urlencoding::encode(postcode)));
67        }
68        if let Some(city) = &self.city {
69            url.push_str(&format!("&city={}", urlencoding::encode(city)));
70        }
71
72        if let Some(ty) = &self.ty {
73            url.push_str(&format!("&type={}", ty));
74        }
75
76        if let Some(limit) = self.limit {
77            url.push_str(&format!("&limit={}", limit));
78        }
79        url
80    }
81
82    /// Executes the reverse geocode query asynchronously.
83    #[cfg(feature = "async")]
84    pub async fn execute_async(&self) -> Result<AddressResult, Error> {
85        self.client.send_async_request(&self.to_url()).await
86    }
87
88    /// Executes the reverse geocode query synchronously.
89    #[cfg(feature = "blocking")]
90    pub fn execute_blocking(&self) -> Result<AddressResult, Error> {
91        self.client.send_blocking_request(&self.to_url())
92    }
93}