latlng 0.1.0

Rust SDK for the latlng.work geocoding and places API
Documentation
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
use serde::{Deserialize, Serialize};

/// Latitude/longitude pair used in places responses.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Coordinates {
    /// Latitude.
    pub lat: f64,
    /// Longitude.
    pub lon: f64,
}

/// A single forward or reverse geocoding result.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GeocodingResult {
    /// Latitude.
    pub lat: f64,
    /// Longitude.
    pub lon: f64,
    /// Display name, when available.
    pub name: Option<String>,
    /// Country name.
    pub country: Option<String>,
    /// State or region.
    pub state: Option<String>,
    /// City or locality.
    pub city: Option<String>,
    /// Postal code.
    pub postcode: Option<String>,
    /// Street name.
    pub street: Option<String>,
    /// House number.
    pub housenumber: Option<String>,
    /// OpenStreetMap key.
    pub osm_key: Option<String>,
    /// OpenStreetMap value.
    pub osm_value: Option<String>,
}

/// Response from a forward or reverse geocoding request.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct GeocodingResponse {
    /// Geocoding results ordered by API relevance.
    pub results: Vec<GeocodingResult>,
}

impl GeocodingResponse {
    /// Returns the first result, if any.
    pub fn first(&self) -> Option<&GeocodingResult> {
        self.results.first()
    }

    /// Returns true when the response has no results.
    pub fn is_empty(&self) -> bool {
        self.results.is_empty()
    }

    /// Number of results in the response.
    pub fn len(&self) -> usize {
        self.results.len()
    }

    /// Iterates over geocoding results.
    pub fn iter(&self) -> impl Iterator<Item = &GeocodingResult> {
        self.results.iter()
    }
}

impl IntoIterator for GeocodingResponse {
    type Item = GeocodingResult;
    type IntoIter = std::vec::IntoIter<GeocodingResult>;

    fn into_iter(self) -> Self::IntoIter {
        self.results.into_iter()
    }
}

impl<'a> IntoIterator for &'a GeocodingResponse {
    type Item = &'a GeocodingResult;
    type IntoIter = std::slice::Iter<'a, GeocodingResult>;

    fn into_iter(self) -> Self::IntoIter {
        self.results.iter()
    }
}

/// A place result returned by nearby, search, or autosuggest endpoints.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Place {
    /// Stable place identifier.
    #[serde(default)]
    pub id: String,
    /// Place display name.
    #[serde(default)]
    pub name: String,
    /// Latitude.
    #[serde(default)]
    pub lat: f64,
    /// Longitude.
    #[serde(default)]
    pub lon: f64,
    /// Place category, such as `restaurant` or `cafe`.
    pub category: Option<String>,
    /// Confidence score, when returned by the API.
    pub confidence: Option<f64>,
    /// Country code or name.
    pub country: Option<String>,
    /// Region or state.
    pub region: Option<String>,
    /// Locality or city.
    pub locality: Option<String>,
    /// City name, when returned by autocomplete responses.
    pub city: Option<String>,
    /// Brand name, when known.
    pub brand: Option<String>,
    /// Distance from the requested point, in meters.
    pub distance_m: Option<f64>,
    /// Search/autosuggest score.
    pub score: Option<f64>,
}

/// Response from `GET /v1/places/nearby`.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct NearbyResponse {
    /// Places near the requested coordinate.
    #[serde(default)]
    pub places: Vec<Place>,
    /// Center point used for the search.
    pub center: Option<Coordinates>,
    /// Search radius in meters.
    pub radius_m: Option<u32>,
    /// Result count reported by the API.
    #[serde(default)]
    pub count: u32,
}

impl NearbyResponse {
    /// Returns true when the response has no places.
    pub fn is_empty(&self) -> bool {
        self.places.is_empty()
    }

    /// Number of places in the response.
    pub fn len(&self) -> usize {
        self.places.len()
    }

    /// Iterates over places.
    pub fn iter(&self) -> impl Iterator<Item = &Place> {
        self.places.iter()
    }
}

impl IntoIterator for NearbyResponse {
    type Item = Place;
    type IntoIter = std::vec::IntoIter<Place>;

    fn into_iter(self) -> Self::IntoIter {
        self.places.into_iter()
    }
}

impl<'a> IntoIterator for &'a NearbyResponse {
    type Item = &'a Place;
    type IntoIter = std::slice::Iter<'a, Place>;

    fn into_iter(self) -> Self::IntoIter {
        self.places.iter()
    }
}

/// Response from `GET /v1/places/search`.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct SearchResponse {
    /// Places matching the query.
    #[serde(default)]
    pub places: Vec<Place>,
    /// Query echoed by the API.
    pub query: Option<String>,
    /// Result count reported by the API.
    #[serde(default)]
    pub count: u32,
}

impl SearchResponse {
    /// Returns true when the response has no places.
    pub fn is_empty(&self) -> bool {
        self.places.is_empty()
    }

    /// Number of places in the response.
    pub fn len(&self) -> usize {
        self.places.len()
    }

    /// Iterates over places.
    pub fn iter(&self) -> impl Iterator<Item = &Place> {
        self.places.iter()
    }
}

/// Response from the autosuggest API.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct AutosuggestResponse {
    /// Suggested places matching the query prefix.
    #[serde(default, alias = "results")]
    pub suggestions: Vec<Place>,
    /// Query echoed by the API.
    pub query: Option<String>,
    /// Result count reported by the API.
    #[serde(default)]
    pub count: u32,
}

impl AutosuggestResponse {
    /// Returns true when the response has no suggestions.
    pub fn is_empty(&self) -> bool {
        self.suggestions.is_empty()
    }

    /// Number of suggestions in the response.
    pub fn len(&self) -> usize {
        self.suggestions.len()
    }

    /// Iterates over suggestions.
    pub fn iter(&self) -> impl Iterator<Item = &Place> {
        self.suggestions.iter()
    }
}

/// A place category and its approximate count.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Category {
    /// Category name.
    pub category: String,
    /// Number of indexed places in this category.
    #[serde(default)]
    pub count: u64,
    /// OpenStreetMap tag backing this category, when returned by the API.
    pub osm_tag: Option<String>,
}

/// Response from `GET /v1/places/categories`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct CategoriesResponse {
    /// Available categories.
    #[serde(default)]
    pub categories: Vec<Category>,
    /// Category count reported by the API.
    #[serde(default)]
    pub count: u32,
}

impl CategoriesResponse {
    /// Returns true when the response has no categories.
    pub fn is_empty(&self) -> bool {
        self.categories.is_empty()
    }

    /// Number of categories in the response.
    pub fn len(&self) -> usize {
        self.categories.len()
    }

    /// Iterates over categories.
    pub fn iter(&self) -> impl Iterator<Item = &Category> {
        self.categories.iter()
    }
}

#[derive(Debug, Deserialize)]
pub(crate) struct FeatureCollection {
    #[serde(default)]
    features: Vec<Feature>,
}

#[derive(Debug, Deserialize)]
struct Feature {
    geometry: Option<Geometry>,
    #[serde(default)]
    properties: GeocodingProperties,
}

#[derive(Debug, Deserialize)]
struct Geometry {
    coordinates: Option<[f64; 2]>,
}

#[derive(Debug, Default, Deserialize)]
struct GeocodingProperties {
    name: Option<String>,
    country: Option<String>,
    state: Option<String>,
    city: Option<String>,
    postcode: Option<String>,
    street: Option<String>,
    housenumber: Option<String>,
    osm_key: Option<String>,
    osm_value: Option<String>,
}

impl From<FeatureCollection> for GeocodingResponse {
    fn from(collection: FeatureCollection) -> Self {
        let results = collection
            .features
            .into_iter()
            .filter_map(|feature| {
                let coordinates = feature.geometry?.coordinates?;
                Some(GeocodingResult {
                    lat: coordinates[1],
                    lon: coordinates[0],
                    name: feature.properties.name,
                    country: feature.properties.country,
                    state: feature.properties.state,
                    city: feature.properties.city,
                    postcode: feature.properties.postcode,
                    street: feature.properties.street,
                    housenumber: feature.properties.housenumber,
                    osm_key: feature.properties.osm_key,
                    osm_value: feature.properties.osm_value,
                })
            })
            .collect();

        Self { results }
    }
}

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

    #[test]
    fn converts_geojson_features_to_geocoding_results() {
        let collection: FeatureCollection = serde_json::from_value(serde_json::json!({
            "type": "FeatureCollection",
            "features": [
                {
                    "type": "Feature",
                    "geometry": {
                        "type": "Point",
                        "coordinates": [13.3888599, 52.5170365]
                    },
                    "properties": {
                        "name": "Berlin",
                        "country": "Germany",
                        "state": "Berlin",
                        "osm_key": "place",
                        "osm_value": "city"
                    }
                }
            ]
        }))
        .expect("valid feature collection");

        let response = GeocodingResponse::from(collection);

        assert_eq!(response.len(), 1);
        let first = response.first().expect("first result");
        assert_eq!(first.name.as_deref(), Some("Berlin"));
        assert_eq!(first.lat, 52.5170365);
        assert_eq!(first.lon, 13.3888599);
        assert_eq!(first.osm_key.as_deref(), Some("place"));
    }

    #[test]
    fn deserializes_nearby_response() {
        let response: NearbyResponse = serde_json::from_value(serde_json::json!({
            "type": "nearby",
            "center": { "lat": 40.748, "lon": -73.985 },
            "radius_m": 500,
            "count": 1,
            "places": [
                {
                    "id": "abc123",
                    "name": "Empire State Building",
                    "category": "attraction",
                    "lat": 40.7484,
                    "lon": -73.9857,
                    "confidence": 0.95,
                    "country": "US",
                    "region": "New York",
                    "locality": "Manhattan",
                    "distance_m": 42
                }
            ]
        }))
        .expect("valid nearby response");

        assert_eq!(response.count, 1);
        assert_eq!(response.radius_m, Some(500));
        assert_eq!(
            response.center.as_ref().map(|center| center.lat),
            Some(40.748)
        );
        let place = response.places.first().expect("first place");
        assert_eq!(place.name, "Empire State Building");
        assert_eq!(place.category.as_deref(), Some("attraction"));
        assert_eq!(place.distance_m, Some(42.0));
    }

    #[test]
    fn deserializes_categories_response_without_counts() {
        let response: CategoriesResponse = serde_json::from_value(serde_json::json!({
            "count": 1,
            "source": "osm_tags",
            "categories": [
                { "category": "restaurant", "osm_tag": "amenity:restaurant" }
            ]
        }))
        .expect("valid categories response");

        assert_eq!(response.count, 1);
        let category = response.categories.first().expect("first category");
        assert_eq!(category.category, "restaurant");
        assert_eq!(category.count, 0);
        assert_eq!(category.osm_tag.as_deref(), Some("amenity:restaurant"));
    }

    #[test]
    fn deserializes_autosuggest_results_alias() {
        let response: AutosuggestResponse = serde_json::from_value(serde_json::json!({
            "query": "eiff",
            "count": 1,
            "results": [
                {
                    "id": "eiffel",
                    "name": "Tour Eiffel",
                    "category": "attraction",
                    "lat": 48.8582599,
                    "lon": 2.2945006,
                    "city": "Paris",
                    "country": "fr"
                }
            ]
        }))
        .expect("valid autosuggest response");

        assert_eq!(response.len(), 1);
        let first = response.suggestions.first().expect("first suggestion");
        assert_eq!(first.name, "Tour Eiffel");
        assert_eq!(first.city.as_deref(), Some("Paris"));
    }
}