[][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.

alt text

Welcome

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(
    // Ensure this date is a weekday in the future or this query will return
    // zero results.
    NaiveDate::from_ymd(2020, 2, 25).and_hms(13, 00, 0)
)
.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);


let time_zone = TimeZoneRequest::new(
     &mut my_settings,
     // St. Vitus Cathedral in Prague, Czechia
     LatLng::try_from(50.090_903, 14.400_512).unwrap(),
     // Tuesday February 23, 2020 @ 6:00:00 pm
     NaiveDate::from_ymd(2020, 2, 23).and_hms(18, 00, 0)
).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.

Structs

AddressComponent

Contains the separate components applicable to this address.

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

Use the ClientSettings struct's implemented methods to set your Google API key and other settings such as: rate limiting, maxium retries, & retry delay times for your requests.

DirectionsDistance

A representation of distance as a numeric value and a display string.

DirectionsDuration

A representation of duration as a numeric value and a display string.

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.

DirectionsResponse

Directions 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.

DistanceMatrixResponse

Distance Matrix responses contain the following root elements.

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.

ElevationResponse

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

Geocoding

When the geocoder returns results, it places them within a results array. Even if the geocoder returns no results (such as if the address doesn't exist) it still returns an empty results array.

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.

GeocodingResponse

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

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.

Geometry

Contains the geocoded latitude/longitude, recommended viewport for displaying the returned result, the bounding box, and other additional data.

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.

Leg

A single leg consisting of a set of steps in a DirectionsResult. Some fields in the leg may not be returned for all requests. Note that though this result is "JSON-like," it is not strictly JSON, as it directly and indirectly includes LatLng objects.

NaiveDate

ISO 8601 calendar date without timezone. Allows for every proleptic Gregorian date from Jan 1, 262145 BCE to Dec 31, 262143 CE. Also supports the conversion from ISO 8601 ordinal and week date.

NaiveDateTime

ISO 8601 combined date and time without timezone.

OverviewPolyline

An encoded polyline representation of the route.

PlusCode

(See Open Location Code and plus codes) is an encoded location reference, derived from latitude and longitude coordinates, that represents an area: 1/8000th of a degree by 1/8000th of a degree (about 14m x 14m at the equator) or smaller. Plus codes can be used as a replacement for street addresses in places where they do not exist (where buildings are not numbered or streets are not named).

Point

Structure for an elevation sample point.

Polyline

An encoded polyline representation of the route.

Route

A single route containing a set of legs in a Response. Note that though this object is "JSON-like," it is not strictly JSON, as it directly and indirectly includes LatLng objects.

Step

Each element in the steps array defines a single step of the calculated directions. A step is the most atomic unit of a direction's route, containing a single step describing a specific, single instruction on the journey. E.g. "Turn left at W. 4th St." The step not only describes the instruction but also contains distance and duration information relating to how this step relates to the following step. For example, a step denoted as "Merge onto I-80 West" may contain a duration of "37 miles" and "40 minutes," indicating that the next step is 37 miles/40 minutes from this step.

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.

TimeZoneResponse

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

TransitAgency

Provides information about the operator of the line.

TransitDetails

Transit directions return additional information that is not relevant for other modes of transportation. These additional properties are exposed through the transit_details object, returned as a field of an element in the steps[] array. From the TransitDetails object you can access additional information about the transit stop, transit line and transit agency.

TransitFare

If present, contains the total fare (that is, the total ticket costs) on this route. This property is only returned for transit requests and only for routes where fare information is available for all transit legs.

TransitLine

Contains the type of vehicle used on this line.

TransitStop

Contains information about the stop/station for this part of the trip.

TransitTime

A representation of time as a Date object, a localized string, and a time zone.

TransitVehicle

Contains the type of vehicle used on this line.

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.

DrivingManeuver

The action to take for the current step (turn left, merge, straight, etc.). This field is used to determine which icon to display. Values in this list are subject to change.

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.

TransitCurrency

A comprehensive list of currencies. At the moment this is used only for Google Maps Transit Directions. The intent behind having Serde convert the currency code String to an enum is for efficient currency conversions, information lookups, and manipulation in the future.

TransitMode

Specifies one or more preferred modes of transit.

TransitRoutePreference

Specifies preferences for transit routes.

TravelMode

Specifies the mode of transportation.

Tz
UnitSystem

Specifies the unit system to use when displaying results.

VehicleType

Indicates the vehicle type

Waypoint

Used to specify pass throughs or stopovers at intermediate locations.