Struct google_maps::GoogleMapsClient
source · pub struct GoogleMapsClient {
pub key: String,
pub rate_limit: RequestRate,
pub reqwest_client: Client,
}
Expand description
Use the GoogleMapsClient
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.
This structure 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.
How to use this structure’s methods in a builder pattern:
let mut my_settings = GoogleMapsClient::new(YOUR_GOOGLE_API_KEY_HERE)
.with_max_delay(std::time::Duration::from_secs(32))
.with_max_retries(10)
.with_rate(Api::All, 1, std::time::Duration::from_secs(2))
.build();
Fields§
§key: String
Your application’s API key. This key identifies your application for purposes of quota management. Learn how to get a key. Contains the application’s API key and other settings.
rate_limit: RequestRate
Rate limits for each of the Google Cloud Maps Platform APIs.
reqwest_client: Client
Allows you to optionally provide your own pre-configured reqwest client that will be used by the Google Maps client.
Implementations§
source§impl GoogleMapsClient
impl GoogleMapsClient
sourcepub fn build(&self) -> GoogleMapsClient
pub fn build(&self) -> GoogleMapsClient
sourcepub fn finalize(&self) -> GoogleMapsClient
pub fn finalize(&self) -> GoogleMapsClient
Completes the builder pattern into a final structure.
GoogleMapsClient::build()
is preferred. finalize
has been kept for
backward compatibility.
Arguments:
This method accepts no arguments.
source§impl GoogleMapsClient
impl GoogleMapsClient
sourcepub fn new(key: &str) -> GoogleMapsClient
pub fn new(key: &str) -> GoogleMapsClient
Initialize the settings needed for a Google Cloud Maps API transaction.
Arguments:
This method accepts no arguments. Use the methods of the resulting type. Use the methods of the resulting type.
sourcepub fn directions(&self, origin: Location, destination: Location) -> Request<'_>
pub fn directions(&self, origin: Location, destination: Location) -> Request<'_>
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.
Basic usage:
use google_maps::prelude::*;
use rust_decimal_macros::dec;
let google_maps_client = GoogleMapsClient::new("YOUR_GOOGLE_API_KEY_HERE");
let directions = google_maps_client.directions(
// 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_dec(dec!(45.403_509), dec!(-75.618_904))?),
)
sourcepub fn distance_matrix(
&self,
origins: Vec<Waypoint>,
destinations: Vec<Waypoint>
) -> Request<'_>
pub fn distance_matrix( &self, origins: Vec<Waypoint>, destinations: Vec<Waypoint> ) -> Request<'_>
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.
Basic usage:
use google_maps::prelude::*;
use rust_decimal_macros::dec;
let google_maps_client = GoogleMapsClient::new("YOUR_GOOGLE_API_KEY_HERE");
let distances = google_maps_client.distance_matrix(
// 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_dec(dec!(37.387_316), dec!(-122.060_008))?),
],
)
sourcepub fn elevation(&self) -> Request<'_>
pub fn elevation(&self) -> Request<'_>
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).
Arguments:
This method accepts no arguments. Use the methods of the resulting type.
sourcepub fn geocoding(&self) -> ForwardRequest<'_>
pub fn geocoding(&self) -> ForwardRequest<'_>
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.
Arguments:
This method accepts no arguments. Use the methods of the resulting type.
sourcepub fn reverse_geocoding(&self, latlng: LatLng) -> ReverseRequest<'_>
pub fn reverse_geocoding(&self, latlng: LatLng) -> ReverseRequest<'_>
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.
Arguments:
latlng
‧ The latitude and longitude values specifying the location for which you wish to obtain the closest, human-readable address.
Basic usage:
use google_maps::prelude::*;
use rust_decimal_macros::dec;
let google_maps_client = GoogleMapsClient::new("YOUR_GOOGLE_API_KEY_HERE");
let address = google_maps_client.reverse_geocoding(
// 10 Downing St, Westminster, London
LatLng::try_from_dec(dec!(51.503_364), dec!(-0.127_625))?,
)
sourcepub fn time_zone(
&self,
location: LatLng,
timestamp: DateTime<Utc>
) -> Request<'_>
pub fn time_zone( &self, location: LatLng, timestamp: DateTime<Utc> ) -> Request<'_>
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.
Arguments:
-
location
‧ Latitude & longitude of the desired time zone location. -
timestamp
‧ Time is used to determine if Daylight Savings is applicable.
Basic usage:
use google_maps::prelude::*;
use rust_decimal_macros::dec;
let google_maps_client = GoogleMapsClient::new("YOUR_GOOGLE_API_KEY_HERE");
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))?,
// Tuesday February 23, 2020 @ 6:00:00 pm
NaiveDate::from_ymd(2020, 2, 23).and_hms(18, 00, 0)
)
sourcepub fn place_autocomplete(&self, input: String) -> Request<'_>
pub fn place_autocomplete(&self, input: String) -> Request<'_>
The Places API Place Autocomplete service returns place predictions. The request specifies a textual search string and optional geographic bounds. The service can be used to provide autocomplete functionality for text-based geographic searches, by returning places such as businesses, addresses and points of interest as a user types.
Arguments:
input
‧ The text string on which to search.
sourcepub fn query_autocomplete(&self, input: String) -> Request<'_>
pub fn query_autocomplete(&self, input: String) -> Request<'_>
The Places API Query Autocomplete service allows you to add on-the-fly geographic query predictions to your application. Instead of searching for a specific location, a user can type in a categorical search, such as “pizza near New York” and the service responds with a list of suggested queries matching the string. As the Query Autocomplete service can match on both full words and substrings, applications can send queries as the user types to provide on-the-fly predictions.
Arguments:
input
‧ The text string on which to search.
Basic usage:
use google_maps::prelude::*;
use rust_decimal_macros::dec;
let google_maps_client = GoogleMapsClient::new("YOUR_GOOGLE_API_KEY_HERE");
let predictions = google_maps_client.place_autocomplete("51".to_string())
.with_location_and_radius(LatLng::try_from_dec(dec!(54), dec!(-114))?, 1_000)
.with_type(AutocompleteType::Address)
.execute()
.await?;
println!("{:#?}", predictions);
sourcepub fn text_search(&self, query: String, radius: u32) -> Request<'_>
pub fn text_search(&self, query: String, radius: u32) -> Request<'_>
The Places API Text Search service 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”. The service responds with a list of places matching the text string and any location bias that has been set.
Arguments:
-
query
‧ The text string on which to search, for example: “restaurant” or “123 Main Street”. This must a place name, address, or category of establishments. Any other types of input can generate errors and are not guaranteed to return valid results. The Google Places service will return candidate matches based on this string and order the results based on their perceived relevance. -
radius
‧ Defines the distance (in meters) within which to return place results. You may bias results to a specified circle by passing alocation
and aradius
parameter. Doing so instructs the Places service to prefer showing results within that circle; results outside of the defined area may still be displayed.
The radius will automatically be clamped to a maximum value depending on the type of search and other parameters.
- Autocomplete: 50,000 meters
- Nearby Search:
- with
keyword
orname
: 50,000 meters - without
keyword
orname
- Up to 50,000 meters, adjusted dynamically based on area
density, independent of
rankby
parameter. - When using
rankby=distance
, the radius parameter will not be accepted, and will result in anINVALID_REQUEST
.
- Up to 50,000 meters, adjusted dynamically based on area
density, independent of
- with
- Query Autocomplete: 50,000 meters
- Nearby Search: 50,000 meters
Additional information:
The service is especially useful for making ambiguous address queries in
an automated system, and non-address components of the string may match
businesses as well as addresses. Examples of ambiguous address queries
are poorly-formatted addresses or requests that include non-address
components such as business names. Requests like the first two examples
below may return ZERO_RESULTS
unless a location bias - such as Region,
Location, or Bounds - is set.
“10 High Street, UK” or “123 Main Street, US” | multiple “High Street“s in the UK; multiple “Main Street“s in the US. Query will not return desirable results unless a location restriction is set. |
---|---|
“ChainRestaurant New York” | multiple “ChainRestaurant” locations in New York; no street address or even street name. Query will not return desirable results unless a location restriction is set. |
“10 High Street, Escher UK” or “123 Main Street, Pleasanton US” | only one “High Street” in the UK city of Escher; only one “Main Street” in the US city of Pleasanton CA. |
“UniqueRestaurantName New York” | only one establishment with this name in New York; no street address needed to differentiate. |
“pizza restaurants in New York” | this query contains its location restriction, and “pizza restaurants” is a well-defined place type. Will yield multiple results, as is expected. |
The search response will include a list of places. You can send a Place Details request for more information about any of the places in the response.
- Nearby Search and Text Search return all of the available data fields for the selected place (a subset of the supported fields), and you will be billed accordingly There is no way to constrain Nearby Search or Text Search to only return specific fields. To keep from requesting (and paying for) data that you don’t need, use a Find Place request instead.
Basic usage:
use google_maps::prelude::*;
use rust_decimal_macros::dec;
let google_maps_client = GoogleMapsClient::new("YOUR_GOOGLE_API_KEY_HERE");
let search_results = google_maps_client.text_search("123 Main Street".to_string(), 50_000)
.with_type(PlaceType::Restaurant)
.execute()
.await?;
println!("{:#?}", search_results);
sourcepub fn nearby_search(&self, location: LatLng, radius: u32) -> Request<'_>
pub fn nearby_search(&self, location: LatLng, radius: u32) -> Request<'_>
The Places API Nearby Search service lets you search for places within a specified area. You can refine your search request by supplying keywords or specifying the type of place you are searching for.
Arguments:
-
location
‧ The point around which to retrieve place information. This must be specified aslatitude,longitude
. -
radius
‧ Defines the distance (in meters) within which to return place results. You may bias results to a specified circle by passing alocation
and aradius
parameter. Doing so instructs the Places service to prefer showing results within that circle; results outside of the defined area may still be displayed.
The radius will automatically be clamped to a maximum value depending on the type of search and other parameters.
- Autocomplete: 50,000 meters
- Nearby Search:
- with
keyword
orname
: 50,000 meters - without
keyword
orname
- Up to 50,000 meters, adjusted dynamically based on area
density, independent of
rankby
parameter. - When using
rankby=distance
, the radius parameter will not be accepted, and will result in anINVALID_REQUEST
.
- Up to 50,000 meters, adjusted dynamically based on area
density, independent of
- with
- Query Autocomplete: 50,000 meters
- Nearby Search: 50,000 meters
Basic usage:
use google_maps::prelude::*;
use rust_decimal_macros::dec;
let google_maps_client = GoogleMapsClient::new("YOUR_GOOGLE_API_KEY_HERE");
let search_results = google_maps_client.nearby_search(LatLng::try_from_dec(dec!(53.540_989), dec!(-113.493_768))?, 1_000)
.with_type(PlaceType::Restaurant)
.execute()
.await?;
println!("{:#?}", search_results);
sourcepub fn place_details(&self, place_id: String) -> Request<'_>
pub fn place_details(&self, place_id: String) -> Request<'_>
The Places API Place Details service returns more details about a particular establishment or point of interest. A Place Details request returns more comprehensive information about the indicated place such as its complete address, phone number, user rating and reviews.
Arguments:
place_id
‧ A textual identifier that uniquely identifies a place, returned from a Place Search. For more information about place IDs, see the place ID overview.
Basic usage:
use google_maps::prelude::*;
use rust_decimal_macros::dec;
let google_maps_client = GoogleMapsClient::new("YOUR_GOOGLE_API_KEY_HERE");
let details = google_maps_client.place_details("ChIJIyEbn74koFMR4xlRm4Ftp6M".to_string())
.execute()
.await?;
println!("{:#?}", details);
sourcepub fn snap_to_roads(&self, path: Vec<LatLng>) -> Request<'_>
pub fn snap_to_roads(&self, path: Vec<LatLng>) -> Request<'_>
The Roads API Snap To Roads service takes up to 100 GPS points collected along a route, and returns a similar set of data, with the points snapped to the most likely roads the vehicle was traveling along. Optionally, you can request that the points be interpolated, resulting in a path that smoothly follows the geometry of the road.
Arguments:
path
‧ The path to be snapped. Note: The snapping algorithm works best for points that are not too far apart. If you observe odd snapping behavior, try creating paths that have points closer together. To ensure the best snap-to-road quality, you should aim to provide paths on which consecutive pairs of points are within 300m of each other. This will also help in handling any isolated, long jumps between consecutive points caused by GPS signal loss, or noise.
Basic usage:
use google_maps::prelude::*;
use rust_decimal_macros::dec;
let google_maps_client = GoogleMapsClient::new("YOUR_GOOGLE_API_KEY_HERE");
let snapped_points = google_maps_client.snap_to_roads(vec![
LatLng::try_from_dec(dec!(-35.27801), dec!(149.12958))?,
LatLng::try_from_dec(dec!(-35.28032), dec!(149.12907))?,
LatLng::try_from_dec(dec!(-35.28099), dec!(149.12929))?,
LatLng::try_from_dec(dec!(-35.28144), dec!(149.12984))?,
LatLng::try_from_dec(dec!(-35.28194), dec!(149.13003))?,
LatLng::try_from_dec(dec!(-35.28282), dec!(149.12956))?,
LatLng::try_from_dec(dec!(-35.28302), dec!(149.12881))?,
LatLng::try_from_dec(dec!(-35.28473), dec!(149.12836))?,
])
.with_interpolation(true)
.execute()
.await?;
sourcepub fn nearest_roads(&self, points: Vec<LatLng>) -> Request<'_>
pub fn nearest_roads(&self, points: Vec<LatLng>) -> Request<'_>
The Roads API Nearest Roads service returns individual road segments for a given set of GPS coordinates. This services takes up to 100 GPS points and returns the closest road segment for each point. The points passed do not need to be part of a continuous path.
If you are working with sequential GPS points, use Nearest Roads.
Arguments:
points
‧ The points to be snapped. The points parameter accepts a list of latitude/longitude pairs.
Basic usage:
use google_maps::prelude::*;
use rust_decimal_macros::dec;
let google_maps_client = GoogleMapsClient::new("YOUR_GOOGLE_API_KEY_HERE");
let snapped_points = google_maps_client.nearest_roads(vec![
LatLng::try_from_dec(dec!(-35.27801), dec!(149.12958))?,
LatLng::try_from_dec(dec!(60.170880), dec!(24.942795))?,
LatLng::try_from_dec(dec!(60.170879), dec!(24.942796))?,
LatLng::try_from_dec(dec!(60.170877), dec!(24.942796))?,
]).execute().await?;
pub async fn get_request(&self, url: &str) -> Result<Response, Error>
source§impl GoogleMapsClient
impl GoogleMapsClient
sourcepub fn with_rate(
&mut self,
api: Api,
requests: u16,
per_duration: Duration
) -> &mut GoogleMapsClient
pub fn with_rate( &mut self, api: Api, requests: u16, per_duration: Duration ) -> &mut GoogleMapsClient
Sets the rate limit for the specified API.
Arguments
-
api
‧ Which Google Maps API are you setting the rate limit for? For example,Api::Directions
,Api::DistanceMatrix
,Api::Elevation
,Api::Geocoding
,Api::TimeZone
, and so on. TheApi::All
rate limit is applied to all Google Maps API requests in addition to the per-API rate limits. -
requests
‧ The number of requests the client library is attempting to target. For example, 2 requests per 1 hour. -
duration
‧ The duration for the targeted request rate. For example, 1 request per 1 minute. This can be defined using thestd::time::Duration
methods.
Examples:
The following examples show how one might try to limit the request rate to achieve maximum throughput while minimizing charges by Google.
The following rates are subject to change by Google. Please review the current Google Maps Platform billing rates.
This Google client library’s rate limiting is not persistent. If your program is often restarted, it is easily possible to exceed Google’s monthly free credit. These are approximations and examples.
To accurately minimize billing charges by Google, please use the Google Cloud Platform Console IAM & admin to set quotas for each API on the server’s side.
You are responsible for all charges. Use with care.
// Assumptions:
// - $200.00 USD monthly free credit from Google. Thanks, guys!
// - 2,629,746 seconds in a month.
const GOOGLE_CREDIT: f64 = 200.0;
const SECONDS_PER_MONTH: u64 = 2_629_746;
- Directions API. You are billed for this SKU when your request does not use live traffic information, arrival or departure times, < 10 waypoints, and no waypoint optimization, $0.005 USD per request.
with_rate(Api::Directions, (GOOGLE_CREDIT / 0.005) as u16, Duration::from_secs(SECONDS_PER_MONTH))
- Directions Advanced API. You are billed for this SKU when your request requires live traffic information, > 10 waypoints, and/or waypoint optimization, $0.01 per request.
with_rate(Api::Directions, (GOOGLE_CREDIT / 0.01) as u16, Duration::from_secs(SECONDS_PER_MONTH))
- Distance Matrix API. You are billed for this SKU when your requests do not require live traffic information, $0.005 per element. The below rate assumes an average of 10 elements per request.
with_rate(
Api::DistanceMatrix,
(GOOGLE_CREDIT / (0.005 * 10.0)) as u16,
Duration::from_secs(SECONDS_PER_MONTH)
)
- Distance Matrix Advanced API. You are billed for this SKU when your requests require live traffic information, $0.01 USD per element. The below rate assumes an average of 10 elements per request.
with_rate(
Api::DistanceMatrix,
(GOOGLE_CREDIT / (0.01 * 10.0)) as u16,
Duration::from_secs(SECONDS_PER_MONTH)
)
- Elevation API. $0.005 USD per request.
with_rate(Api::Elevation, (GOOGLE_CREDIT / 0.005) as u16, Duration::from_secs(SECONDS_PER_MONTH))
- Geocoding API. $0.005 USD per request.
with_rate(Api::Geocoding, (GOOGLE_CREDIT / 0.005) as u16, Duration::from_secs(SECONDS_PER_MONTH))
- Time Zone API. $0.005 USD per request.
with_rate(Api::TimeZone, (GOOGLE_CREDIT / 0.005) as u16, Duration::from_secs(SECONDS_PER_MONTH))
source§impl GoogleMapsClient
impl GoogleMapsClient
sourcepub fn with_reqwest_client(
&mut self,
reqwest_client: Client
) -> &mut GoogleMapsClient
pub fn with_reqwest_client( &mut self, reqwest_client: Client ) -> &mut GoogleMapsClient
Passes a user configured reqwest client for the Google Maps client to use. This allows the you to have more control over the how the Google Maps client connects to the Google Maps server.
Mause mentioned that this feature could be useful for writing tests. Thanks for the suggestion!
Arguments
reqwest_client
‧ A reqwest client built using thereqwest::Client::builder()
function.
Examples:
let reqwest_client = reqwest::Client::builder()
.user_agent("My Cool App v1.0")
.build()?;
let mut google_maps_client = GoogleMapsClient::new("YOUR_API_KEY_HERE")
.with_reqwest_client(reqwest_client)
.build();
pub fn with_reqwest_middleware_client( &mut self, reqwest_client: ClientWithMiddleware ) -> &mut GoogleMapsClient
pub fn with_reqwest(&mut self, reqwest_client: Client) -> &mut GoogleMapsClient
Trait Implementations§
source§impl Clone for GoogleMapsClient
impl Clone for GoogleMapsClient
source§fn clone(&self) -> GoogleMapsClient
fn clone(&self) -> GoogleMapsClient
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read more