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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
//! The [OpenStreetMap Nominatim](https://nominatim.org/) provider.
//!
//! Geocoding methods are implemented on the [`Openstreetmap`](struct.Openstreetmap.html) struct.
//! Please see the [API documentation](https://nominatim.org/release-docs/develop/) for details.
//!
//! While OpenStreetMap's Nominatim API is free, see the [Nominatim Usage Policy](https://operations.osmfoundation.org/policies/nominatim/)
//! for details on usage requirements, including a maximum of 1 request per second.
//!
//! ### Example
//!
//! ```
//! use geocoding::{Openstreetmap, Forward, Point};
//!
//! let osm = Openstreetmap::new();
//! let address = "Schwabing, München";
//! let res = osm.forward(&address);
//! assert_eq!(res.unwrap(), vec![Point::new(11.5884858, 48.1700887)]);
//! ```
use crate::GeocodingError;
use crate::InputBounds;
use crate::Point;
use crate::UA_STRING;
use crate::{Client, HeaderMap, HeaderValue, USER_AGENT};
use crate::{Deserialize, Serialize};
use crate::{Forward, Reverse};
use num_traits::Float;
use std::fmt::Debug;

/// An instance of the Openstreetmap geocoding service
pub struct Openstreetmap {
    client: Client,
    endpoint: String,
}

/// An instance of a parameter builder for Openstreetmap geocoding
pub struct OpenstreetmapParams<'a, T>
where
    T: Float + Debug,
{
    query: &'a str,
    addressdetails: bool,
    viewbox: Option<&'a InputBounds<T>>,
}

impl<'a, T> OpenstreetmapParams<'a, T>
where
    T: Float + Debug,
{
    /// Create a new OpenStreetMap parameter builder
    /// # Example:
    ///
    /// ```
    /// use geocoding::{Openstreetmap, InputBounds, Point};
    /// use geocoding::openstreetmap::{OpenstreetmapParams};
    ///
    /// let viewbox = InputBounds::new(
    ///     (-0.13806939125061035, 51.51989264641164),
    ///     (-0.13427138328552246, 51.52319711775629),
    /// );
    /// let params = OpenstreetmapParams::new(&"UCL CASA")
    ///     .with_addressdetails(true)
    ///     .with_viewbox(&viewbox)
    ///     .build();
    /// ```
    pub fn new(query: &'a str) -> OpenstreetmapParams<'a, T> {
        OpenstreetmapParams {
            query,
            addressdetails: false,
            viewbox: None,
        }
    }

    /// Set the `addressdetails` property
    pub fn with_addressdetails(&mut self, addressdetails: bool) -> &mut Self {
        self.addressdetails = addressdetails;
        self
    }

    /// Set the `viewbox` property
    pub fn with_viewbox(&mut self, viewbox: &'a InputBounds<T>) -> &mut Self {
        self.viewbox = Some(viewbox);
        self
    }

    /// Build and return an instance of OpenstreetmapParams
    pub fn build(&self) -> OpenstreetmapParams<'a, T> {
        OpenstreetmapParams {
            query: self.query,
            addressdetails: self.addressdetails,
            viewbox: self.viewbox,
        }
    }
}

impl Openstreetmap {
    /// Create a new Openstreetmap geocoding instance using the default endpoint
    pub fn new() -> Self {
        Openstreetmap::new_with_endpoint("https://nominatim.openstreetmap.org/".to_string())
    }

    /// Create a new Openstreetmap geocoding instance with a custom endpoint.
    ///
    /// Endpoint should include a trailing slash (i.e. "https://nominatim.openstreetmap.org/")
    pub fn new_with_endpoint(endpoint: String) -> Self {
        let mut headers = HeaderMap::new();
        headers.insert(USER_AGENT, HeaderValue::from_static(UA_STRING));
        let client = Client::builder()
            .default_headers(headers)
            .build()
            .expect("Couldn't build a client!");
        Openstreetmap { client, endpoint }
    }

    /// A forward-geocoding lookup of an address, returning a full detailed response
    ///
    /// Accepts an [`OpenstreetmapParams`](struct.OpenstreetmapParams.html) struct for specifying
    /// options, including whether to include address details in the response and whether to filter
    /// by a bounding box.
    ///
    /// Please see [the documentation](https://nominatim.org/release-docs/develop/api/Search/) for details.
    ///
    /// This method passes the `format` parameter to the API.
    ///
    /// # Examples
    ///
    /// ```
    /// use geocoding::{Openstreetmap, InputBounds, Point};
    /// use geocoding::openstreetmap::{OpenstreetmapParams, OpenstreetmapResponse};
    ///
    /// let osm = Openstreetmap::new();
    /// let viewbox = InputBounds::new(
    ///     (-0.13806939125061035, 51.51989264641164),
    ///     (-0.13427138328552246, 51.52319711775629),
    /// );
    /// let params = OpenstreetmapParams::new(&"UCL CASA")
    ///     .with_addressdetails(true)
    ///     .with_viewbox(&viewbox)
    ///     .build();
    /// let res: OpenstreetmapResponse<f64> = osm.forward_full(&params).unwrap();
    /// let result = res.features[0].properties.clone();
    /// assert!(result.display_name.contains("Gordon Square"));
    /// ```
    pub fn forward_full<T>(
        &self,
        params: &OpenstreetmapParams<T>,
    ) -> Result<OpenstreetmapResponse<T>, GeocodingError>
    where
        T: Float + Debug,
        for<'de> T: Deserialize<'de>,
    {
        let format = String::from("geojson");
        let addressdetails = String::from(if params.addressdetails { "1" } else { "0" });
        // For lifetime issues
        let viewbox;

        let mut query = vec![
            (&"q", params.query),
            (&"format", &format),
            (&"addressdetails", &addressdetails),
        ];

        if let Some(vb) = params.viewbox {
            viewbox = String::from(*vb);
            query.push((&"viewbox", &viewbox));
        }

        let resp = self
            .client
            .get(&format!("{}search", self.endpoint))
            .query(&query)
            .send()?
            .error_for_status()?;
        let res: OpenstreetmapResponse<T> = resp.json()?;
        Ok(res)
    }
}

impl Default for Openstreetmap {
    fn default() -> Self {
        Self::new()
    }
}

impl<T> Forward<T> for Openstreetmap
where
    T: Float + Debug,
    for<'de> T: Deserialize<'de>,
{
    /// A forward-geocoding lookup of an address. Please see [the documentation](https://nominatim.org/release-docs/develop/api/Search/) for details.
    ///
    /// This method passes the `format` parameter to the API.
    fn forward(&self, place: &str) -> Result<Vec<Point<T>>, GeocodingError> {
        let resp = self
            .client
            .get(&format!("{}search", self.endpoint))
            .query(&[(&"q", place), (&"format", &String::from("geojson"))])
            .send()?
            .error_for_status()?;
        let res: OpenstreetmapResponse<T> = resp.json()?;
        Ok(res
            .features
            .iter()
            .map(|res| Point::new(res.geometry.coordinates.0, res.geometry.coordinates.1))
            .collect())
    }
}

impl<T> Reverse<T> for Openstreetmap
where
    T: Float + Debug,
    for<'de> T: Deserialize<'de>,
{
    /// A reverse lookup of a point. More detail on the format of the
    /// returned `String` can be found [here](https://nominatim.org/release-docs/develop/api/Reverse/)
    ///
    /// This method passes the `format` parameter to the API.
    fn reverse(&self, point: &Point<T>) -> Result<Option<String>, GeocodingError> {
        let resp = self
            .client
            .get(&format!("{}reverse", self.endpoint))
            .query(&[
                (&"lon", &point.x().to_f64().unwrap().to_string()),
                (&"lat", &point.y().to_f64().unwrap().to_string()),
                (&"format", &String::from("geojson")),
            ])
            .send()?
            .error_for_status()?;
        let res: OpenstreetmapResponse<T> = resp.json()?;
        let address = &res.features[0];
        Ok(Some(address.properties.display_name.to_string()))
    }
}

/// The top-level full GeoJSON response returned by a forward-geocoding request
///
/// See [the documentation](https://nominatim.org/release-docs/develop/api/Search/#geojson) for more details
///
///```json
///{
///  "type": "FeatureCollection",
///  "licence": "Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright",
///  "features": [
///    {
///      "type": "Feature",
///      "properties": {
///        "place_id": 263681481,
///        "osm_type": "way",
///        "osm_id": 355421084,
///        "display_name": "68, Carrer de Calatrava, les Tres Torres, Sarrià - Sant Gervasi, Barcelona, BCN, Catalonia, 08017, Spain",
///        "place_rank": 30,
///        "category": "building",
///        "type": "apartments",
///        "importance": 0.7409999999999999,
///        "address": {
///          "house_number": "68",
///          "road": "Carrer de Calatrava",
///          "suburb": "les Tres Torres",
///          "city_district": "Sarrià - Sant Gervasi",
///          "city": "Barcelona",
///          "county": "BCN",
///          "state": "Catalonia",
///          "postcode": "08017",
///          "country": "Spain",
///          "country_code": "es"
///        }
///      },
///      "bbox": [
///        2.1284918,
///        41.401227,
///        2.128952,
///        41.4015815
///      ],
///      "geometry": {
///        "type": "Point",
///        "coordinates": [
///          2.12872241167437,
///          41.40140675
///        ]
///      }
///    }
///  ]
///}
///```
#[derive(Debug, Serialize, Deserialize)]
pub struct OpenstreetmapResponse<T>
where
    T: Float + Debug,
{
    pub r#type: String,
    pub licence: String,
    pub features: Vec<OpenstreetmapResult<T>>,
}

/// A geocoding result
#[derive(Debug, Serialize, Deserialize)]
pub struct OpenstreetmapResult<T>
where
    T: Float + Debug,
{
    pub r#type: String,
    pub properties: ResultProperties,
    pub bbox: (T, T, T, T),
    pub geometry: ResultGeometry<T>,
}

/// Geocoding result properties
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ResultProperties {
    pub place_id: u64,
    pub osm_type: String,
    pub osm_id: u64,
    pub display_name: String,
    pub place_rank: u64,
    pub category: String,
    pub r#type: String,
    pub importance: f64,
    pub address: Option<AddressDetails>,
}

/// Address details in the result object
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AddressDetails {
    pub city: Option<String>,
    pub city_district: Option<String>,
    pub construction: Option<String>,
    pub continent: Option<String>,
    pub country: Option<String>,
    pub country_code: Option<String>,
    pub house_number: Option<String>,
    pub neighbourhood: Option<String>,
    pub postcode: Option<String>,
    pub public_building: Option<String>,
    pub state: Option<String>,
    pub suburb: Option<String>,
}

/// A geocoding result geometry
#[derive(Debug, Serialize, Deserialize)]
pub struct ResultGeometry<T>
where
    T: Float + Debug,
{
    pub r#type: String,
    pub coordinates: (T, T),
}

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

    #[test]
    fn new_with_endpoint_forward_test() {
        let osm =
            Openstreetmap::new_with_endpoint("https://nominatim.openstreetmap.org/".to_string());
        let address = "Schwabing, München";
        let res = osm.forward(&address);
        assert_eq!(res.unwrap(), vec![Point::new(11.5884858, 48.1700887)]);
    }

    #[test]
    fn forward_full_test() {
        let osm = Openstreetmap::new();
        let viewbox = InputBounds::new(
            (-0.13806939125061035, 51.51989264641164),
            (-0.13427138328552246, 51.52319711775629),
        );
        let params = OpenstreetmapParams::new(&"UCL CASA")
            .with_addressdetails(true)
            .with_viewbox(&viewbox)
            .build();
        let res: OpenstreetmapResponse<f64> = osm.forward_full(&params).unwrap();
        let result = res.features[0].properties.clone();
        assert!(result.display_name.contains("Gordon Square"));
        assert_eq!(result.address.unwrap().city.unwrap(), "London");
    }

    #[test]
    fn forward_test() {
        let osm = Openstreetmap::new();
        let address = "Schwabing, München";
        let res = osm.forward(&address);
        assert_eq!(res.unwrap(), vec![Point::new(11.5884858, 48.1700887)]);
    }

    #[test]
    fn reverse_test() {
        let osm = Openstreetmap::new();
        let p = Point::new(2.12870, 41.40139);
        let res = osm.reverse(&p);
        assert!(res
            .unwrap()
            .unwrap()
            .contains("Barcelona, Barcelonès, Barcelona, Catalunya"));
    }
}