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
use serde_json; use google::{ GoogleResponse, STATUS_NO_RESULTS, STATUS_OK, STATUS_OVER_LIMIT, ERR_OVER_LIMIT, ERR_NO_RESULTS, }; use url::Url; use structs::*; use cabot::{RequestBuilder, Client}; pub const BASE_URL: &str = "http://www.datasciencetoolkit.org/maps/api/geocode/json"; pub fn geocode(address: &str) -> Result<GeocodeResponse, String> { let mut url = Url::parse(BASE_URL).unwrap(); url.query_pairs_mut().append_pair("address", address); let request = RequestBuilder::new(url.as_str()) .set_http_method("GET") .build() .unwrap(); let client = Client::new(); let raw_response = client.execute(&request).unwrap(); let response: GoogleResponse = serde_json::from_slice( raw_response.body().unwrap() ) .unwrap(); return match response.status.as_str() { STATUS_OK => Ok(GeocodeResponse { location: response.results[0].clone().geometry.location, location_type: response.results[0].clone().geometry.location_type, formatted_address: address.to_string() , }), STATUS_NO_RESULTS => Err(ERR_NO_RESULTS.to_string()), STATUS_OVER_LIMIT => Err(ERR_OVER_LIMIT.to_string()), _ => Err(response.status), }; }