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),
};
}