[][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.403_509, -75.618_904).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, 6).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.387_316, -122.060_008).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.739_154, -104.984_703).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.503_364, -0.127_625).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.090_903, 14.400_512).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. Track both requests and request elements for rate limiting.
  2. Make a generic get() function for that can be used by all APIs.
  3. Look into making APIs optional, i.e. features.
  4. Look into the Prelude::* convention.
  5. Look into integrating yaiouom.
  6. Convert explicit query validation to session types wherever reasonable.
  7. 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.
  8. Roads 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.

Re-exports

pub extern crate time;

Structs

Bounds

Contains the recommended viewport for displaying the returned result, specified as two latitude & longitude values defining the southwest and northeast corner of the viewport bounding box. Generally the viewport is used to frame a result when displaying it to a user.

ClientSettings

Contains your API key - the preferred way for authenticating with the Google Maps Platform APIs, your request rate limit settings, and your automatic retry settings.

Date

Calendar date.

Directions

Directions responses contain the following root elements.

DirectionsRequest

Look at this Request struct for documentation on how to build your Directions API query. The methods implemented for this struct are what's used to build your request.

DistanceMatrix

Distance Matrix responses contain the following root elements.

DistanceMatrixRequest

Look at this Request struct for documentation on how to build your Distance Matrix API query. The methods implemented for this struct are what's used to build your request.

Duration

A Duration type to represent a span of time, typically used for system timeouts.

Elevation

The response from the Google Maps Elevation API is stored in this structure.

ElevationRequest

Look at this Request struct for documentation on how to build your Time Zone API query. The methods implemented for this struct are what's used to build your request.

Geocoding

The response from the Google Maps Geolocation API will be stored in this structure.

GeocodingForwardRequest

Look at this Request struct for documentation on how to build your Geocoding API query. The methods implemented for this struct are what's used to build your request. Forward geocoding looks up a longitude & latitude coordinates from a street address.

GeocodingRequest

Look at this Request struct for documentation on how to build your Geocoding API query. The methods implemented for this struct are what's used to build your request. Forward geocoding looks up a longitude & latitude coordinates from a street address.

GeocodingReverseRequest

Look at this Request struct for documentation on how to build your Geocoding API query. The methods implemented for this struct are what's used to build your request. Reverse geocoding looks up a street address from latitude & longitude coorindates.

Instant

A measurement of a monotonically nondecreasing clock. Opaque and useful only with Duration.

LatLng

Latitude and longitude values must correspond to a valid location on the face of the earth. Latitudes can take any value between -90 and 90 while longitude values can take any value between -180 and 180. If you specify an invalid latitude or longitude value, your request will be rejected as a bad request.

PrimitiveDateTime

Combined date and time.

Time

The clock time within a given date. Nanosecond precision.

TimeZone

The response from the Google Maps Time Zone API will be stored in this structure.

TimeZoneRequest

Look at this Request struct for documentation on how to build your Time Zone API query. The methods implemented for this struct are what's used to build your request.

Enums

Api

Api is used to select an API to configure.

Avoid

Used to specify features that calculated routes should avoid.

DepartureTime

Specifies the desired time of departure.

DirectionsStatus

The status field within the Directions response object contains the status of the request, and may contain debugging information to help you track down why the Directions service failed.

DistanceMatrixStatus

The status fields within the response object contain the status of the request, and may contain useful debugging information. The Distance Matrix API returns a top-level status field, with information about the request in general, as well as a status field for each element field, with information about that particular origin-destination pairing.

ElevationError

Errors that may be produced by the Google Maps Elevation API client.

ElevationLocations

Defines the location(s) on the earth from which to return elevation data.

ElevationStatus

Indicates the status of the response.

GeocodingComponent

The components filter is accepted as an optional parameter if an address is provided. In a Geocoding response, the Geocoding API can return address results restricted to a specific area. You can specify the restriction using the components filter. A filter consists of a list of component:value pairs separated by a pipe (|). Filter values support the same methods of spelling correction and partial matching as other Geocoding requests. If the geocoder finds a partial match for a component filter, the response will contain a partial_match field.

GeocodingError

Errors that may be produced by the Google Maps Geocoding API client.

GeocodingStatus

Indicates the status of the response.

Language

Specifies the language in which to return results.

Location

Used to specify the address, latitude/longitude, or place ID for the origin and destination.

LocationType

Stores additional data about the specified location.

PlaceType

Place Types

Region

Specifies the region bias.

TimeZoneError

Errors that may be produced by the Google Maps Time Zone API client.

TimeZoneStatus

Indicates the status of the response.

TrafficModel

Specifies the traffic model to use when calculating time in traffic.

TransitMode

Specifies one or more preferred modes of transit.

TransitRoutePreference

Specifies preferences for transit routes.

TravelMode

Specifies the mode of transportation.

UnitSystem

Specifies the unit system to use when displaying results.

Waypoint

Used to specify pass throughs or stopovers at intermediate locations.