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 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
//! The [GeoAdmin](https://api3.geo.admin.ch) provider for geocoding in Switzerland exclusively.
//!
//! Based on the [Search API](https://api3.geo.admin.ch/services/sdiservices.html#search)
//! and [Identify Features API](https://api3.geo.admin.ch/services/sdiservices.html#identify-features)
//!
//! While GeoAdmin API is free, please respect their fair usage policy.
//!
//! ### Example
//!
//! ```
//! # tokio_test::block_on(async {
//! use geocoding_async::{GeoAdmin, Forward, Point};
//!
//! let geoadmin = GeoAdmin::new();
//! let address = "Seftigenstrasse 264, 3084 Wabern";
//! let res = geoadmin.forward(&address).await;
//! assert_eq!(res.unwrap(), vec![Point::new(7.451352119445801, 46.92793655395508)]);
//! # });
//! ```
use crate::Deserialize;
use crate::GeocodingError;
use crate::InputBounds;
use crate::Point;
use crate::UA_STRING;
use crate::{Client, HeaderMap, HeaderValue, USER_AGENT};
use crate::{Forward, Reverse};
use num_traits::{Float, Pow};
use std::fmt::Debug;
/// An instance of the GeoAdmin geocoding service
pub struct GeoAdmin {
client: Client,
endpoint: String,
sr: String,
}
/// An instance of a parameter builder for GeoAdmin geocoding
pub struct GeoAdminParams<'a, T>
where
T: Float + Debug,
{
searchtext: &'a str,
origins: &'a str,
bbox: Option<&'a InputBounds<T>>,
limit: Option<u8>,
}
impl<'a, T> GeoAdminParams<'a, T>
where
T: Float + Debug,
{
/// Create a new GeoAdmin parameter builder
/// # Example:
///
/// ```
/// use geocoding_async::{GeoAdmin, InputBounds, Point};
/// use geocoding_async::geoadmin::{GeoAdminParams};
///
/// let bbox = InputBounds::new(
/// (7.4513398, 46.92792859),
/// (7.4513662, 46.9279467),
/// );
/// let params = GeoAdminParams::new(&"Seftigenstrasse Bern")
/// .with_origins("address")
/// .with_bbox(&bbox)
/// .build();
/// ```
pub fn new(searchtext: &'a str) -> GeoAdminParams<'a, T> {
GeoAdminParams {
searchtext,
origins: "zipcode,gg25,district,kantone,gazetteer,address,parcel",
bbox: None,
limit: Some(50),
}
}
/// Set the `origins` property
pub fn with_origins(&mut self, origins: &'a str) -> &mut Self {
self.origins = origins;
self
}
/// Set the `bbox` property
pub fn with_bbox(&mut self, bbox: &'a InputBounds<T>) -> &mut Self {
self.bbox = Some(bbox);
self
}
/// Set the `limit` property
pub fn with_limit(&mut self, limit: u8) -> &mut Self {
self.limit = Some(limit);
self
}
/// Build and return an instance of GeoAdminParams
pub fn build(&self) -> GeoAdminParams<'a, T> {
GeoAdminParams {
searchtext: self.searchtext,
origins: self.origins,
bbox: self.bbox,
limit: self.limit,
}
}
}
impl GeoAdmin {
/// Create a new GeoAdmin geocoding instance using the default endpoint and sr
pub fn new() -> Self {
GeoAdmin::default()
}
/// Set a custom endpoint of a GeoAdmin geocoding instance
///
/// Endpoint should include a trailing slash (i.e. "https://api3.geo.admin.ch/rest/services/api/")
pub fn with_endpoint(mut self, endpoint: &str) -> Self {
endpoint.clone_into(&mut self.endpoint);
self
}
/// Set a custom sr of a GeoAdmin geocoding instance
///
/// Supported values: 21781 (LV03), 2056 (LV95), 4326 (WGS84) and 3857 (Web Pseudo-Mercator)
pub fn with_sr(mut self, sr: &str) -> Self {
sr.clone_into(&mut self.sr);
self
}
/// A forward-geocoding search of a location, returning a full detailed response
///
/// Accepts an [`GeoAdminParams`](struct.GeoAdminParams.html) struct for specifying
/// options, including what origins to response and whether to filter
/// by a bounding box.
///
/// Please see [the documentation](https://api3.geo.admin.ch/services/sdiservices.html#search) for details.
///
/// This method passes the `format` parameter to the API.
///
/// # Examples
///
/// ```
/// # tokio_test::block_on(async {
/// use geocoding_async::{GeoAdmin, InputBounds, Point};
/// use geocoding_async::geoadmin::{GeoAdminParams, GeoAdminForwardResponse};
///
/// let geoadmin = GeoAdmin::new();
/// let bbox = InputBounds::new(
/// (7.4513398, 46.92792859),
/// (7.4513662, 46.9279467),
/// );
/// let params = GeoAdminParams::new(&"Seftigenstrasse Bern")
/// .with_origins("address")
/// .with_bbox(&bbox)
/// .build();
/// let res: GeoAdminForwardResponse<f64> = geoadmin.forward_full(¶ms).await.unwrap();
/// let result = &res.features[0];
/// assert_eq!(
/// result.properties.label,
/// "Seftigenstrasse 264 <b>3084 Wabern</b>",
/// );
/// # });
/// ```
pub async fn forward_full<T>(
&self,
params: &GeoAdminParams<'_, T>,
) -> Result<GeoAdminForwardResponse<T>, GeocodingError>
where
T: Float + Debug,
for<'de> T: Deserialize<'de>,
{
// For lifetime issues
let bbox;
let limit;
let mut query = vec![
("searchText", params.searchtext),
("type", "locations"),
("origins", params.origins),
("sr", &self.sr),
("geometryFormat", "geojson"),
];
if let Some(bb) = params.bbox.cloned().as_mut() {
if ["4326", "3857"].contains(&self.sr.as_str()) {
*bb = InputBounds::new(
wgs84_to_lv03(&bb.minimum_lonlat),
wgs84_to_lv03(&bb.maximum_lonlat),
);
}
bbox = String::from(*bb);
query.push(("bbox", &bbox));
}
if let Some(lim) = params.limit {
limit = lim.to_string();
query.push(("limit", &limit));
}
let resp = self
.client
.get(&format!("{}SearchServer", self.endpoint))
.query(&query)
.send()
.await?
.error_for_status()?;
let res: GeoAdminForwardResponse<T> = resp.json().await?;
Ok(res)
}
}
impl Default for GeoAdmin {
fn default() -> 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!");
GeoAdmin {
client,
endpoint: "https://api3.geo.admin.ch/rest/services/api/".to_string(),
sr: "4326".to_string(),
}
}
}
impl<T> Forward<T> for GeoAdmin
where
T: Float + Debug,
for<'de> T: Deserialize<'de>,
{
/// A forward-geocoding lookup of an address. Please see [the documentation](https://api3.geo.admin.ch/services/sdiservices.html#search) for details.
///
/// This method passes the `type`, `origins`, `limit` and `sr` parameter to the API.
async fn forward(&self, place: &str) -> Result<Vec<Point<T>>, GeocodingError> {
let resp = self
.client
.get(&format!("{}SearchServer", self.endpoint))
.query(&[
("searchText", place),
("type", "locations"),
("origins", "address"),
("limit", "1"),
("sr", &self.sr),
("geometryFormat", "geojson"),
])
.send()
.await?
.error_for_status()?;
let res: GeoAdminForwardResponse<T> = resp.json().await?;
// return easting & northing consistent
let results = if ["2056", "21781"].contains(&self.sr.as_str()) {
res.features
.iter()
.map(|feature| Point::new(feature.properties.y, feature.properties.x)) // y = west-east, x = north-south
.collect()
} else {
res.features
.iter()
.map(|feature| Point::new(feature.properties.x, feature.properties.y)) // x = west-east, y = north-south
.collect()
};
Ok(results)
}
}
impl<T> Reverse<T> for GeoAdmin
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://api3.geo.admin.ch/services/sdiservices.html#identify-features)
///
/// This method passes the `format` parameter to the API.
async fn reverse(&self, point: &Point<T>) -> Result<Option<String>, GeocodingError> {
let resp = self
.client
.get(&format!("{}MapServer/identify", self.endpoint))
.query(&[
(
"geometry",
format!(
"{},{}",
point.x().to_f64().unwrap(),
point.y().to_f64().unwrap()
)
.as_str(),
),
("geometryType", "esriGeometryPoint"),
("layers", "all:ch.bfs.gebaeude_wohnungs_register"),
("mapExtent", "0,0,100,100"),
("imageDisplay", "100,100,100"),
("tolerance", "50"),
("geometryFormat", "geojson"),
("sr", &self.sr),
("lang", "en"),
])
.send()
.await?
.error_for_status()?;
let res: GeoAdminReverseResponse = resp.json().await?;
if !res.results.is_empty() {
let properties = &res.results[0].properties;
let address = format!(
"{}, {} {}",
properties.strname_deinr, properties.dplz4, properties.dplzname
);
Ok(Some(address))
} else {
Ok(None)
}
}
}
// Approximately transform Point from WGS84 to LV03
//
// See [the documentation](https://www.swisstopo.admin.ch/content/swisstopo-internet/en/online/calculation-services/_jcr_content/contentPar/tabs/items/documents_publicatio/tabPar/downloadlist/downloadItems/19_1467104393233.download/ch1903wgs84_e.pdf) for more details
fn wgs84_to_lv03<T>(p: &Point<T>) -> Point<T>
where
T: Float + Debug,
{
let lambda = (p.x().to_f64().unwrap() * 3600.0 - 26782.5) / 10000.0;
let phi = (p.y().to_f64().unwrap() * 3600.0 - 169028.66) / 10000.0;
let x = 2600072.37 + 211455.93 * lambda
- 10938.51 * lambda * phi
- 0.36 * lambda * phi.pow(2)
- 44.54 * lambda.pow(3);
let y = 1200147.07 + 308807.95 * phi + 3745.25 * lambda.pow(2) + 76.63 * phi.pow(2)
- 194.56 * lambda.pow(2) * phi
+ 119.79 * phi.pow(3);
Point::new(
T::from(x - 2000000.0).unwrap(),
T::from(y - 1000000.0).unwrap(),
)
}
/// The top-level full JSON (GeoJSON Feature Collection) response returned by a forward-geocoding request
///
/// See [the documentation](https://api3.geo.admin.ch/services/sdiservices.html#search) for more details
///
///```json
///{
/// "type": "FeatureCollection",
/// "features": [
/// {
/// "properties": {
/// "origin": "address",
/// "geom_quadindex": "021300220302203002031",
/// "weight": 1512,
/// "zoomlevel": 10,
/// "lon": 7.451352119445801,
/// "detail": "seftigenstrasse 264 3084 wabern 355 koeniz ch be",
/// "rank": 7,
/// "lat": 46.92793655395508,
/// "num": 264,
/// "y": 2600968.75,
/// "x": 1197427.0,
/// "label": "Seftigenstrasse 264 <b>3084 Wabern</b>"
/// "id": 1420809,
/// }
/// }
/// ]
/// }
///```
#[derive(Debug, Deserialize)]
pub struct GeoAdminForwardResponse<T>
where
T: Float + Debug,
{
pub features: Vec<GeoAdminForwardLocation<T>>,
}
/// A forward geocoding location
#[derive(Debug, Deserialize)]
pub struct GeoAdminForwardLocation<T>
where
T: Float + Debug,
{
pub properties: ForwardLocationProperties<T>,
}
/// Forward Geocoding location attributes
#[derive(Clone, Debug, Deserialize)]
pub struct ForwardLocationProperties<T> {
pub origin: String,
pub geom_quadindex: String,
pub weight: u32,
pub rank: u32,
pub detail: String,
pub lat: T,
pub lon: T,
pub num: Option<usize>,
pub x: T,
pub y: T,
pub label: String,
pub zoomlevel: u32,
}
/// The top-level full JSON (GeoJSON FeatureCollection) response returned by a reverse-geocoding request
///
/// See [the documentation](https://api3.geo.admin.ch/services/sdiservices.html#identify-features) for more details
///
///```json
/// {
/// "results": [
/// {
/// "type": "Feature"
/// "id": "1272199_0"
/// "attributes": {
/// "xxx": "xxx",
/// "...": "...",
/// },
/// "layerBodId": "ch.bfs.gebaeude_wohnungs_register",
/// "layerName": "Register of Buildings and Dwellings",
/// }
/// ]
/// }
///```
#[derive(Debug, Deserialize)]
pub struct GeoAdminReverseResponse {
pub results: Vec<GeoAdminReverseLocation>,
}
/// A reverse geocoding result
#[derive(Debug, Deserialize)]
pub struct GeoAdminReverseLocation {
#[serde(rename = "featureId")]
pub feature_id: String,
#[serde(rename = "layerBodId")]
pub layer_bod_id: String,
#[serde(rename = "layerName")]
pub layer_name: String,
pub properties: ReverseLocationAttributes,
}
/// Reverse geocoding result attributes
#[derive(Clone, Debug, Deserialize)]
pub struct ReverseLocationAttributes {
pub egid: Option<String>,
pub ggdenr: u32,
pub ggdename: String,
pub gdekt: String,
pub edid: Option<String>,
pub egaid: u32,
pub deinr: Option<String>,
pub dplz4: u32,
pub dplzname: String,
pub egrid: Option<String>,
pub esid: u32,
pub strname: Vec<String>,
pub strsp: Vec<String>,
pub strname_deinr: String,
pub label: String,
}
#[cfg(test)]
mod test {
use super::*;
#[tokio::test]
async fn new_with_sr_forward_test() {
let geoadmin = GeoAdmin::new().with_sr("2056");
let address = "Seftigenstrasse 264, 3084 Wabern";
let res = geoadmin.forward(&address).await;
assert_eq!(res.unwrap(), vec![Point::new(2_600_968.75, 1_197_427.0)]);
}
#[tokio::test]
async fn new_with_endpoint_forward_test() {
let geoadmin =
GeoAdmin::new().with_endpoint("https://api3.geo.admin.ch/rest/services/api/");
let address = "Seftigenstrasse 264, 3084 Wabern";
let res = geoadmin.forward(&address).await;
assert_eq!(
res.unwrap(),
vec![Point::new(7.451352119445801, 46.92793655395508)]
);
}
#[tokio::test]
async fn with_sr_forward_full_test() {
let geoadmin = GeoAdmin::new().with_sr("2056");
let bbox = InputBounds::new((2_600_967.75, 1_197_426.0), (2_600_969.75, 1_197_428.0));
let params = GeoAdminParams::new(&"Seftigenstrasse Bern")
.with_origins("address")
.with_bbox(&bbox)
.build();
let res: GeoAdminForwardResponse<f64> = geoadmin.forward_full(¶ms).await.unwrap();
let result = &res.features[0];
assert_eq!(
result.properties.label,
"Seftigenstrasse 264 <b>3084 Wabern</b>",
);
}
#[tokio::test]
async fn forward_full_test() {
let geoadmin = GeoAdmin::new();
let bbox = InputBounds::new((7.4513398, 46.92792859), (7.4513662, 46.9279467));
let params = GeoAdminParams::new(&"Seftigenstrasse Bern")
.with_origins("address")
.with_bbox(&bbox)
.build();
let res: GeoAdminForwardResponse<f64> = geoadmin.forward_full(¶ms).await.unwrap();
let result = &res.features[0];
assert_eq!(
result.properties.label,
"Seftigenstrasse 264 <b>3084 Wabern</b>",
);
}
#[tokio::test]
async fn forward_test() {
let geoadmin = GeoAdmin::new();
let address = "Seftigenstrasse 264, 3084 Wabern";
let res = geoadmin.forward(&address).await;
assert_eq!(
res.unwrap(),
vec![Point::new(7.451352119445801, 46.92793655395508)]
);
}
#[tokio::test]
async fn with_sr_reverse_test() {
let geoadmin = GeoAdmin::new().with_sr("2056");
let p = Point::new(2_600_968.75, 1_197_427.0);
let res = geoadmin.reverse(&p).await;
assert_eq!(
res.unwrap(),
Some("Seftigenstrasse 264, 3084 Wabern".to_string()),
);
}
#[tokio::test]
#[ignore = "https://github.com/georust/geocoding/pull/45#issuecomment-1592395700"]
async fn reverse_test() {
let geoadmin = GeoAdmin::new();
let p = Point::new(7.451352119445801, 46.92793655395508);
let res = geoadmin.reverse(&p).await;
assert_eq!(
res.unwrap(),
Some("Seftigenstrasse 264, 3084 Wabern".to_string()),
);
}
}