[−][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
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:
- Track both requests and request elements for rate limiting.
- Make a generic get() function for that can be used by all APIs.
- Look into making APIs optional, i.e. features.
- Look into the Prelude::* convention.
- Look into integrating yaiouom.
- Convert explicit query validation to session types wherever reasonable.
- 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.
- 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 |
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 |
DirectionsResponse | Directions responses contain the following root elements. |
DistanceMatrixRequest | Look at this |
DistanceMatrixResponse | Distance Matrix responses contain the following root elements. |
ElevationRequest | Look at this |
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 |
GeocodingResponse | The response from the Google Maps Geolocation API will be stored in this structure. |
GeocodingReverseRequest | Look at this |
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 |
Step | Each element in the |
TimeZoneRequest | Look at this |
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 |
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 |
|
Avoid | Used to specify features that calculated routes should avoid. |
DepartureTime | Specifies the desired time of departure. |
DirectionsStatus | The |
DistanceMatrixStatus | The |
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 |
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 | |
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 |
TransitMode | Specifies one or more preferred modes of transit. |
TransitRoutePreference | Specifies preferences for transit routes. |
TransitTimeZone | A comprehensive list of time zones. At the moment this is used only for
Google Maps Transit Directions. The intent behind having Serde convert
the time zone |
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. |