Expand description
§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, Time Zone API, and parts of the Places and Roads API.
§Installation
Configure the dependencies:
[dependencies]
google_maps = "3.9"Optionally, add rust_decimal = "1" and rust_decimal_macros = "1" for
access to the dec! macro. This macro can be used to define decimal numbers
in your program.
This is useful for hard-coding latitudes and longitudes into your code for testing.
§Feature Flags
The desired Google Maps APIs can be enabled individually via feature flags.
Additionally, usage of rustls for Reqwest is supported.
§Google Maps Client Feature Flags:
address_validation‧ includes Google Maps Address Validation APIdirections‧ includes Google Maps Directions APIdistance_matrix‧ includes Google Maps Distance Matrix APIelevation‧ includes Google Maps Elevation APIgeocoding‧ includes Google Maps Geocoding APIroads‧ includes Google Maps Roads APItime_zone‧ includes Google Maps Time Zone APIreqwest‧ uses reqwest for querying the Google Maps APIreqwest-middleware‧ uses reqwest-middleware for querying the Google Maps APIgeo‧ support for the rust geo ecosystempolyline‧ allows easy type conversions from aRouteorStepto a geo LineString
§Google Maps Places API (New) Features
places-new‧ includes all Google Maps Places API (New) servicesplaces-new-autocomplete‧ Autocomplete service onlyplaces-new-nearby-search‧ Nearby Search service onlyplaces-new-place-details‧ Place Details service onlyplaces-new-place-photos‧ Place Photos service onlyplaces-new-text-search‧ Text Search service only
§Google Maps Places API (Legacy) Features
autocomplete‧ includes Google Maps Places API (Legacy) Autocomplete serviceplaces‧ includes Google Maps Places API (Legacy)
Note: the autocomplete feature covers the Places API autocomplete-related services:
Place Autocomplete requests
and Query Autocomplete requests.
All other Places API services are covered by the places feature.
§Default Feature Flags
By default, the Google Maps client includes all implemented Google Maps APIs. Reqwest will secure
the connection using the system-native TLS (native-tls), and has gzip compression
enabled (gzip).
default = [
# google_maps default features:
"address_validation",
"directions",
"distance_matrix",
"elevation",
"geocoding",
"time_zone",
"roads",
"places-new",
# reqwest default features:
"reqwest",
"reqwest-default-tls",
"reqwest-http2",
"reqwest-brotli",
# rust_decimal default features:
"decimal-serde",
]§Feature flag usage example
This example will only include the Google Maps Directions API. Reqwest will secure the connection using the Rustls library, and has brotli compression enabled.
google_maps = {
version = "3.9",
default-features = false,
features = [
"directions",
"reqwest",
"reqwest-rustls-tls",
"reqwest-brotli"
]
}§Release Notes
The full changelog is available here.
Releases are available on GitHub.
§Examples
§Autocomplete
Autocomplete (New) is a web service that returns place predictions and query predictions in response to an HTTP request. In the request, specify a text search string and geographic bounds that controls the search area.
Autocomplete (New) can match on full words and substrings of the input, resolving place names, addresses, and plus codes. Applications can therefore send queries as the user types, to provide on-the-fly place and query predictions.
let google_maps_client = google_maps::Client::try_new("YOUR_API_KEY_HERE")?;
let response = google_maps_client
.autocomplete("pizza")
.included_primary_types(vec![google_maps::places_new::PlaceType::Restaurant])
.execute()
.await?;
for suggestion in &response {
println!("{}", suggestion.text());
}
// User adds "sicilian" to pizza search:
let response = google_maps_client
.next_autocomplete("pizza sicilian", response)
.await?;
for suggestion in response {
println!("{}", suggestion.to_html("mark"));
}§Text Search
Text Search (New) returns information about a set of places based on a string (for example, “pizza in New York” or “shoe stores near Ottawa” or “123 Main Street”).
let google_maps_client = google_maps::Client::try_new("YOUR_API_KEY_HERE")?;
let response = google_maps_client
.text_search("Gas in Edmonton, Alberta")
.field_mask(google_maps::places_new::FieldMask::All)
.execute()
.await?;
for place in response {
println!("{place:#?}");
}§Nearby Search
A Nearby Search (New) request takes one or more place types, and returns a list of matching places within the specified area.
let google_maps_client = google_maps::Client::try_new("YOUR_API_KEY_HERE")?;
// Restaurants within a 5,000 m radius of the Bowker Building in Edmonton
let response = google_maps_client
.nearby_search((53.53666, -113.50795, 5_000.0))?
.field_mask(google_maps::places_new::FieldMask::All)
.included_primary_types(vec![google_maps::places_new::PlaceType::Restaurant])
.execute()
.await?;
for place in response {
println!("{place:#?}");
}§Place Details
Once you have a place ID, you can request more details about a particular establishment or point of interest by initiating a Place Details (New) request.
A Place Details (New) request returns more comprehensive information about the indicated place such as its complete address, phone number, user rating and reviews.
There are many ways to obtain a place ID. You can use:
- Text Search (New) or Nearby Search (New)
- Geocoding API
- Routes API
- Address Validation API
- Autocomplete (New)
You can also experiment using the Place ID Finder
let google_maps_client = google_maps::Client::try_new("YOUR_API_KEY_HERE")?;
let place = google_maps_client
.place_details("ChIJyZXV1jsioFMRC8PGIBAJbKA")?
.field_mask(google_maps::places_new::FieldMask::All)
.execute()
.await?;
println!("{place:#?}");§Place Photos
The Place Photos (New) service is a read-only API that lets you add high quality photographic content to your application. Place Photos (New) gives you access to the millions of photos stored in the Places database.
When you get place information using a Place Details (New), Nearby Search (New), or Text Search (New) request, you can also request photo resources for relevant photographic content. Using Place Photos (New), you can then access the referenced photos and resize the image to the optimal size for your application.
for place in response.into_iter().take(3) {
// Download and display photo as ASCII art. `places-new-ascii-art` feature must be enabled
if let Ok(photo) = google_maps_client
.place_photos_image(&place)?
.max_width_px(1_024)
.execute()
.await
{
println!("{}", photo.display_ansi(
std::num::NonZero::new(180).unwrap() // 180 columns wide
)?);
}
}§Address Validation
The Address Validation API validates an address and its components, standardizes the address for mailing, and determines the best known geocode for it.
use google_maps::prelude::*;
let google_maps_client = google_maps::Client::try_new("YOUR_API_KEY_HERE")?;
let postal_address = PostalAddress::builder()
.region_code(&Country::UnitedStates)
.address_lines(vec![
"1600 Amphitheatre Pkwy",
"Mountain View, CA, 94043"
])
.build();
let address_validation_response = google_maps_client
.validate_address()
.address(postal_address)
.build()
.execute()
.await?;
// Dump entire response:
println!("{address_validation_response:#?}");
// Optional feedback step. Let Google know which address was used for the
// your query:
google_maps_client
.provide_validation_feedback()
.conclusion(ValidationConclusion::Unused)
.response_id(address_validation_response.response_id())
.build()
.execute()
.await?;§Directions API
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.
use google_maps::prelude::*;
let google_maps_client = Client::try_new("YOUR_GOOGLE_API_KEY_HERE");
// Example request:
let directions = google_maps_client.directions(
// Origin: Canadian Museum of Nature
Location::from_address("240 McLeod St, Ottawa, ON K2P 2R1"),
// Destination: Canada Science and Technology Museum
Location::try_from_f32(45.403_509, -75.618_904)?,
)
.with_travel_mode(TravelMode::Driving)
.execute()
.await?;
// Dump entire response:
println!("{:#?}", directions);§Distance Matrix API
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.
use google_maps::prelude::*;
let google_maps_client = Client::try_new("YOUR_GOOGLE_API_KEY_HERE");
// Example request:
let distance_matrix = google_maps_client.distance_matrix(
// Origins
vec![
// Microsoft
Waypoint::from_address("One Microsoft Way, Redmond, WA 98052, United States"),
// Cloudflare
Waypoint::from_address("101 Townsend St, San Francisco, CA 94107, United States"),
],
// Destinations
vec![
// Google
Waypoint::from_place_id("ChIJj61dQgK6j4AR4GeTYWZsKWw"),
// Mozilla
Waypoint::try_from_f32(37.387_316, -122.060_008)?,
],
).execute().await?;
// Dump entire response:
println!("{:#?}", distance_matrix);§Elevation API (Positional)
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).
use google_maps::prelude::*;
let google_maps_client = Client::try_new("YOUR_GOOGLE_API_KEY_HERE");
// Example request:
let elevation = google_maps_client.elevation()
// Denver, Colorado, the "Mile High City"
.for_positional_request(LatLng::try_from_dec(dec!(39.739_154), dec!(-104.984_703))?)
.execute()
.await?;
// Dump entire response:
println!("{:#?}", elevation);
// Display all results:
if let Some(results) = &elevation.results {
for result in results {
println!("Elevation: {} meters", result.elevation)
}
}§Geocoding API
The Geocoding API is a service that provides geocoding and reverse geocoding of addresses. Geocoding is the process of converting addresses (like a street address) into geographic coordinates (like latitude and longitude), which you can use to place markers on a map, or position the map.
use google_maps::prelude::*;
let google_maps_client = Client::try_new("YOUR_GOOGLE_API_KEY_HERE");
// Example request:
let location = google_maps_client.geocoding()
.with_address("10 Downing Street London")
.execute()
.await?;
// Dump entire response:
println!("{:#?}", location);
// Print latitude & longitude coordinates:
for result in location.results {
println!("{}", result.geometry.location)
}§Reverse Geocoding API
The Geocoding API is a service that provides geocoding and reverse geocoding of addresses. Reverse geocoding is the process of converting geographic coordinates into a human-readable address.
use google_maps::prelude::*;
let google_maps_client = Client::try_new("YOUR_GOOGLE_API_KEY_HERE");
// Example request:
let location = google_maps_client.reverse_geocoding(
// 10 Downing St, Westminster, London
LatLng::try_from_dec(dec!(51.503_364), dec!(-0.127_625))?,
)
.with_result_type(PlaceType::StreetAddress)
.execute()
.await?;
// Dump entire response:
println!("{:#?}", location);
// Display all results:
for result in location.results {
println!(
"{}",
result.address_components.iter()
.map(|address_component| address_component.short_name.to_string())
.collect::<Vec<String>>()
.join(", ")
);
}§Time Zone API
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.
use google_maps::prelude::*;
let google_maps_client = Client::try_new("YOUR_GOOGLE_API_KEY_HERE");
// Example request:
let time_zone = google_maps_client.time_zone(
// St. Vitus Cathedral in Prague, Czechia
LatLng::try_from_dec(dec!(50.090_903), dec!(14.400_512))?,
// The time right now in UTC (Coordinated Universal Time)
Utc::now()
).execute().await?;
// Dump entire response:
println!("{:#?}", time_zone);
// Usage example:
println!("Time at your computer: {}", Local::now().to_rfc2822());
if let Some(time_zone_id) = time_zone.time_zone_id {
println!(
"Time in {}: {}",
time_zone_id.name(),
Utc::now().with_timezone(&time_zone_id).to_rfc2822()
);
}§Controlling Request Settings
The Google Maps client settings can be used to change the request rate and automatic retry parameters.
use google_maps::prelude::*;
let google_maps_client = Client::try_new("YOUR_GOOGLE_API_KEY_HERE")
// For all Google Maps Platform APIs, the client will limit 2 sucessful
// requests for every 10 seconds:
.with_rate(&Api::All, 2, std::time::Duration::from_secs(10))
// Returns the `Client` struct to the caller. This struct is used
// to make Google Maps Platform requests.
.build();§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!
§Roadmap
- Track both requests and request elements for rate limiting.
- Convert explicit query validation to session types wherever reasonable.
- Places API. Only partly implemented. If you would like to have any missing pieces implemented, please contact me.
- Roads API. Only partly implemented. If you would like to have any missing pieces implemented, please contact me.
§Author’s Note
This crate is expected to work well and have the more important Google Maps features implemented. It should work well because serde, serde-json and, by default, reqwest do most of the heavy lifting!
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.
Re-exports§
Modules§
- address_
validation - The Address Validation API validates an address and its components, standardize the address for mailing, and determine the best known geocode for it.
- 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).
- error
- Google Maps Platform API error types and error messages.
- 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.
- places_
new - Places API (New) - Get location data for over 200 million places, and add place details, search, and autocomplete to your apps.
- prelude
- Put
use google_maps::prelude::*;in your code will to get more convenient access to everything you need. If you’re not concerned with name space collisions or conflicts, you can glob import allgoogle_mapsstructs and enums by using this module. - roads
- Roads API - Identify the roads a vehicle is traveling along, and get metadata about those roads.
- 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.
- traits
- Contains
traitdeclarations that are used internally in thegoogle_mapscrate. - types
- Common types used across several Google Maps API interfaces.
Structs§
- Address
Component - Contains the separate components applicable to this address.
- Bounds
- Contains the recommended viewport for displaying the returned result, specified as two latitude & longitude pairs 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.
- Client
- Use the
GoogleMapsClientstruct’s implemented methods to set your Google API key and other settings such as: rate limiting, maxium retries, & retry delay times for your requests. - Client
Settings - Use the
GoogleMapsClientstruct’s implemented methods to set your Google API key and other settings such as: rate limiting, maxium retries, & retry delay times for your requests. - Geometry
- Contains the geocoded latitude/longitude, recommended viewport for displaying the returned result, the bounding box, and other additional data.
- Google
Maps Client - Use the
GoogleMapsClientstruct’s implemented methods to set your Google API key and other settings such as: rate limiting, maxium retries, & retry delay times for your requests. - LatLng
- Represents a geographic coordinate on Earth’s surface.
Enums§
- Api
Apiis used to select an API to configure. For example, the Google Maps Client can be set to have different request rates forDirectionsandElevationrequests. Thisenumis used to select which Google Maps API you would like to configure.- Classified
Error - Used to classify errors and API response statuses as
None,TransientorPermanent. - Country
- Country is the national political entity and is typically the highest order type returned by the Geocoder.
- Language
- Specifies the language in which to return results.
- Location
Type - Stores additional data about the specified location.
- Place
Type - This specifies the types or categories of a place. For example, a returned
location could be a “country” (as in a nation) or it could be a “shopping
mall.” Also, a requested place could be a “locality” (a city) or a
“
street_address” This type helps define the data that is being returned or sought. See Place Types for more information. - Region
- Specifies the region bias.
- Type
Error - Errors that may be produced by crate types from implementations and associated functions. For example, type conversions, instantiations, etc.