[][src]Crate google_maps

google_maps

An unofficial Google Maps Platform client library for the Rust programming language. This client currently implements the Directions API, Distance Matrix API, Elevation API, Geocoding API, and Time Zone API.

Welcome

There are many breaking changes with version 0.4.0. Please review the new examples and change log on how to reformat your code if it no longer compiles.

This crate is expected to work well and have the more important Google Maps features implemented. It should work well because Reqwest and Serde do most of the heavy lifting! While it's an early release, this crate should work fine as is for most people.

I created this client library because I needed several Google Maps Platform features for a project that I'm working on. So, I've decided to spin my library off into a public crate. This is a very small token of gratitude and an attempt to give back to the Rust community. I hope it saves someone out there some work.

Example Directions API Request

use google_maps::*;
let mut my_settings = ClientSettings::new(YOUR_GOOGLE_API_KEY_HERE);

// Example request:

let directions = DirectionsRequest::new(
    &mut my_settings,
    // Origin: Canadian Museum of Nature
    Location::Address(String::from("240 McLeod St, Ottawa, ON K2P 2R1")),
    // Destination: Canada Science and Technology Museum
    Location::LatLng(LatLng::try_from(45.403509, -75.618904).unwrap()),
)
.with_travel_mode(TravelMode::Transit)
.with_arrival_time(PrimitiveDateTime::new(
    // Ensure this date is a weekday in the future or this query will return
    // zero results.
    Date::try_from_ymd(2020, 2, 06).unwrap(),
    Time::try_from_hms(13, 00, 0).unwrap()
))
.execute().unwrap();

// Dump entire response:

println!("{:#?}", directions);

Example Distance Matrix API Request

use google_maps::*;
let mut my_settings = ClientSettings::new(YOUR_GOOGLE_API_KEY_HERE);

// Example request:

let distance_matrix = DistanceMatrixRequest::new(
    &mut my_settings,
    // Origins
    vec![
        // Microsoft
        Waypoint::Address(String::from("One Microsoft Way, Redmond, WA 98052, United States")),
        // Cloudflare
        Waypoint::Address(String::from("101 Townsend St, San Francisco, CA 94107, United States")),
    ],
    // Destinations
    vec![
        // Google
        Waypoint::PlaceId(String::from("ChIJj61dQgK6j4AR4GeTYWZsKWw")),
        // Mozilla
        Waypoint::LatLng(LatLng::try_from(37.387316, -122.060008).unwrap()),
    ],
)
.execute().unwrap();

// Dump entire response:

println!("{:#?}", distance_matrix);

Example Elevation API Positional Request

use google_maps::*;
let mut my_settings = ClientSettings::new(YOUR_GOOGLE_API_KEY_HERE);

// Example request:

let elevation = ElevationRequest::new(&mut my_settings)
// Denver, Colorado, the "Mile High City"
.for_positional_request(LatLng::try_from(39.7391536, -104.9847034).unwrap())
.execute().unwrap();

// Dump entire response:

println!("{:#?}", elevation);

// Parsing example:

println!("Elevation: {} meters", elevation.results.unwrap()[0].elevation);

Example Geocoding API Request

use google_maps::*;
let mut my_settings = ClientSettings::new(YOUR_GOOGLE_API_KEY_HERE);

// Example request:

let location = GeocodingRequest::new(&mut my_settings)
    .with_address("10 Downing Street London")
    .execute().unwrap();

// Dump entire response:

println!("{:#?}", location);

// Parsing example:

for result in &location.results {
    println!("{}", result.geometry.location)
}

Example Reverse Geocoding API Request

use google_maps::*;
let mut my_settings = ClientSettings::new(YOUR_GOOGLE_API_KEY_HERE);

// Example request:

let location = GeocodingReverseRequest::new(
    &mut my_settings,
    // 10 Downing St, Westminster, London
    LatLng::try_from(51.5033635, -0.1276248).unwrap(),
)
.with_result_type(PlaceType::StreetAddress)
.execute().unwrap();

// Dump entire response:

println!("{:#?}", location);

// Parsing example:

for result in &location.results {
    for address_component in &result.address_components {
        print!("{} ", address_component.short_name);
    }
    println!(""); // New line.
}

Example Time Zone API Request

use google_maps::*;
let mut my_settings = ClientSettings::new(YOUR_GOOGLE_API_KEY_HERE);

// Example request:

let time_zone = TimeZoneRequest::new(
    &mut my_settings,
    // St. Vitus Cathedral in Prague, Czechia
    LatLng::try_from(50.090903, 14.400512).unwrap(),
    PrimitiveDateTime::new(
        // Tuesday February 15, 2022
        Date::try_from_ymd(2022, 2, 15).unwrap(),
        // 6:00:00 pm
        Time::try_from_hms(18, 00, 0).unwrap(),
    ),
).execute().unwrap();

// Dump entire response:

println!("{:#?}", time_zone);

// Parsing example:

use std::time::{SystemTime, UNIX_EPOCH};

let unix_timestamp =
    SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();

println!("Time at your computer: {}", unix_timestamp);

println!("Time in {}: {}",
    time_zone.time_zone_id.unwrap(),
    unix_timestamp as i64 + time_zone.dst_offset.unwrap() as i64 +
        time_zone.raw_offset.unwrap() as i64
);

Geolocation API

Google's Geolocation API seems to be offline. While the online documentation is still available and the API appears configurable through the Google Cloud Platform console, the Geolocation API responds Status code 404 Not Found with an empty body to all requests. This API cannot be implemented until the server responds as expected.

Feedback

I would like for you to be successful with your project! If this crate is not working for you, doesn't work how you think it should, or if you have requests, or suggestions - please report them to me! I'm not always fast at responding but I will respond. Thanks!

To do:

  1. Convert explicit query validation to session types wherever reasonable.

  2. Places API. There are no immediate plans for supporting this API. It's quite big and I have no current need for it. If you would like to have to implemented, please contact me.

  3. Roads API. There are no immediate plans for supporting this API. It's quite big and I have current need for it. If you would like to have to implemented, please contact me.

Re-exports

pub extern crate time;
pub use crate::bounds::Bounds;
pub use crate::client_settings::ClientSettings;
pub use crate::language::Language;
pub use crate::latlng::LatLng;
pub use crate::place_type::PlaceType;
pub use crate::region::Region;
pub use crate::directions::request::avoid::Avoid;
pub use crate::directions::request::departure_time::DepartureTime;
pub use crate::directions::request::location::Location;
pub use crate::directions::request::Request as DirectionsRequest;
pub use crate::directions::request::traffic_model::TrafficModel;
pub use crate::directions::request::transit_mode::TransitMode;
pub use crate::directions::request::transit_route_preference::TransitRoutePreference;
pub use crate::directions::request::unit_system::UnitSystem;
pub use crate::directions::request::waypoint::Waypoint;
pub use crate::directions::response::Response as Directions;
pub use crate::directions::response::status::Status as DirectionsStatus;
pub use crate::directions::travel_mode::TravelMode;
pub use crate::distance_matrix::request::Request as DistanceMatrixRequest;
pub use crate::distance_matrix::response::Response as DistanceMatrix;
pub use crate::distance_matrix::response::status::Status as DistanceMatrixStatus;
pub use crate::elevation::error::Error as ElevationError;
pub use crate::elevation::request::locations::Locations as ElevationLocations;
pub use crate::elevation::request::Request as ElevationRequest;
pub use crate::elevation::response::Response as Elevation;
pub use crate::elevation::response::status::Status as ElevationStatus;
pub use crate::geocoding::error::Error as GeocodingError;
pub use crate::geocoding::forward::component::Component as GeocodingComponent;
pub use crate::geocoding::forward::ForwardRequest as GeocodingForwardRequest;
pub use crate::geocoding::forward::ForwardRequest as GeocodingRequest;
pub use crate::geocoding::location_type::LocationType;
pub use crate::geocoding::response::Response as Geocoding;
pub use crate::geocoding::response::status::Status as GeocodingStatus;
pub use crate::geocoding::reverse::ReverseRequest as GeocodingReverseRequest;
pub use crate::time_zone::error::Error as TimeZoneError;
pub use crate::time_zone::request::Request as TimeZoneRequest;
pub use crate::time_zone::response::Response as TimeZone;
pub use crate::time_zone::response::status::Status as TimeZoneStatus;

Modules

bounds

Contains the Bounds struct and its associated traits. It is used to specify a selection or bounding box over a geographic area using two latitude & longitude pairs.

client_settings

Contains the ClientSettings struct and its associated traits. It is used to set your API key and the settings such as: rate limiting, maxium retries, & retry delay times for your requests.

directions

The Directions API is a service that calculates directions between locations. You can search for directions for several modes of transportation, including transit, driving, walking, or cycling.

distance_matrix

The Distance Matrix API is a service that provides travel distance and time for a matrix of origins and destinations, based on the recommended route between start and end points.

elevation

The Elevation API provides elevation data for all locations on the surface of the earth, including depth locations on the ocean floor (which return negative values).

geocoding

The Geocoding API is a service that provides geocoding and reverse geocoding of addresses. It can be used to convert a street address to geographic coordinates (latitude & longitude), or vice versa.

language

Contains the Language enum and its associated traits. It is used to specify a desired language for a response. This is not a comprehensive list of languages, it is a list of languages that Google Maps supports.

latlng

Contains the LatLng struct, its associated traits, and functions. The latitude & longitude coorindate system is used to specify a position or location on the Earth's surface.

place_type

Contains the PlaceType enum and its associated traits. It specifies the types or categories of a place. For example, a returned place could be a "country" (as in a nation) or it could be a "shopping mall."

region

Contains the Region enum and its associated traits. It is used to specify a country in which Google Maps has been officially launched. Google's regions uses ccTLDs rather than ISO 3166 country codes. This is not a comprehensive list of countries, it is a list of countries that Google Maps supports.

request_rate

Contains the RequestRate struct and its associated traits. It is used to specify Google Maps Platform and per-API request rate limits.

time_zone

The Time Zone API provides time offset data for locations on the surface of the earth. You request the time zone information for a specific latitude/longitude pair and date. The API returns the name of that time zone, the time offset from UTC, and the daylight savings offset.

Structs

Date

Calendar date.

PrimitiveDateTime

Combined date and time.

Time

The clock time within a given date. Nanosecond precision.