use reqwest::Client;
use crate::{errors::GeocoderError, structs::GeocodeResponse};
pub struct Geocoder {
api_key: String,
client: Client,
}
impl Geocoder {
pub fn new(api_key: &str) -> Geocoder {
Self {
api_key: api_key.to_string(),
client: Client::new(),
}
}
pub async fn geocode(&self, location: &str) -> Result<GeocodeResponse, GeocoderError> {
let url = format!(
"https://maps.googleapis.com/maps/api/geocode/json?address={}&key={}",
location, self.api_key
);
let response = self.client.get(&url).send().await?;
let body: serde_json::Value = response.json().await?;
let geocode_response: GeocodeResponse = match serde_json::from_value(body) {
Ok(response) => response,
Err(e) => return Err(GeocoderError::ParseError(e)),
};
if geocode_response.results.is_empty() {
return Err(GeocoderError::AddressNotFound);
}
Ok(geocode_response)
}
}