@googlemaps/google-maps-services-js

repository·master·Indexed 25 days ago

https://github.com/googlemaps/google-maps-services-js

A Node.js client library for accessing Google Maps Web Services APIs. It provides access to standard APIs such as Maps Static, Elevation, Geocoding, Roads, and Time Zone, as well as legacy versions of the Directions, Places, and Distance Matrix APIs. The library features TypeScript support, Promise-based returns, and configurable Axios settings for retries and timeouts.

Tokens
11.5K
Snippets
21
Records
68
Agent score
79%

What's inside @googlemaps/google-maps-services-js

  1. Initialize and use the Google Maps Client

    master

    The library is designed for server-side Node.js applications. You can import the Client using ES6 modules (TypeScript) or CommonJS. Methods take an object containing params, timeout, and optionally headers or an axiosInstance. Note that the API key is configured within the params object of each method call, rather than at the client instantiation level.

    import {Client} from "@googlemaps/google-maps-services-js";
    
    const client = new Client({});
    
    client
      .elevation({
        params: {
          locations: [{ lat: 45, lng: -110 }],
          key: process.env.MAPS_API_KEY,
        },
        timeout: 1000, // milliseconds
      })
      .then((r) => {
        console.log(r.data.results[0].elevation);
      })
      .catch((e) => {
        console.log(e.response.data.error_message);
      });
  2. Migrate from @google/maps to @googlemaps/google-maps-services-js

    master

    The new library differs significantly from the old @google/maps package. Key differences include:

    • Parameter Passing: Instead of individual arguments, methods now take an object containing params, headers, body, instance, and timeout.
    • API Key Configuration: The API key is now passed within the params object of each method call, not during client creation.
    • Promises: Promises are now the default return type.
    • Typings: TypeScript types are included in the package (previously required @types/googlemaps).
    • Advanced Features: Supports keep-alive, interceptors, cancellation, and configurable retries (via axios-retry or retry-axios).
  3. Use the Google Maps Services Node.js Client

    master
    The @googlemaps/google-maps-services-js library provides a client for interacting with various Google Maps Platform services in a Node.js environment. The main entry point exports a Client class and various request/response types for different services including Directions, Distance Matrix, Elevation, Geocoding, Places, Roads, and Time Zone. To use the library, you typically instantiate a Client and call its service-specific methods using the appropriate request objects.
  4. Authenticate using Google Maps Platform Premium Plan

    master

    For legacy applications using the Google Maps Platform Premium Plan, you can authenticate using a client_id and client_secret within the params object of your method calls.

    const client = new Client({});
    
    client
      .elevation({
        params: {
          locations: [{ lat: 45, lng: -110 }],
          client_id: process.env.GOOGLE_MAPS_CLIENT_ID,
          client_secret: process.env.GOOGLE_MAPS_CLIENT_SECRET
        },
        timeout: 1000
      })
      .then(r => {
        console.log(r.data.results[0].elevation);
      })
      .catch(e => {
        console.log(e.response.data.error_message);
      });
  5. Get elevation data with elevation()

    master
    Use the elevation() function to retrieve elevation data for specific locations or along a path. The function accepts an ElevationRequest object containing params and optional Axios configuration. It returns a Promise that resolves to an ElevationResponse containing an array of results, each including the location, elevation (in meters), and resolution.
  6. Define Latitude and Longitude (LatLng)

    master

    The LatLng type is flexible and accepts several formats for representing geographic coordinates. You can use:

    • A two-item array: [latitude, longitude]
    • A comma-separated string: 'latitude,longitude'
    • An object with lat and lng properties: { lat: number, lng: number }
    • An object with latitude and longitude properties: { latitude: number, longitude: number }
    export type LatLng =
      | LatLngArray
      | LatLngString
      | LatLngLiteral
      | LatLngLiteralVerbose;
  7. Get place details with placeDetails()

    master

    Use the placeDetails function to retrieve detailed information about a specific place using its place_id.

    Warning: Field Masking You must specify the desired data types in the fields parameter. If you omit the fields parameter, the API will return ALL possible fields, and you will be billed for the most expensive tier of data.

    Parameters:

    • params.place_id (string): A unique identifier for the place (usually obtained from a Place Search).
    • params.fields (string[]): An array of strings specifying the types of place data to return. These are returned as a comma-separated list in the request.
    • params.language (Language, optional): The language code for the results.
    • params.region (string, optional): A two-character ccTLD region code.
    • params.sessiontoken (string, optional): A token to associate the request with an autocomplete session for billing purposes.
    • params.key (string, required via RequestParams): Your Google Maps API key.
  8. Initialize the Google Maps Client

    master

    The Client class is a wrapper around Google Maps API methods that provides shared configuration for Axios settings, including retry logic (via retry-axios) and gzip encoding. You can instantiate the client in three ways:

    1. With defaults: Uses default timeout (10000ms), default HTTPS agent, and default retry settings.
    2. With a config object: Provides custom AxiosRequestConfig (including raxConfig for retries).
    3. With an existing Axios instance: For advanced use cases where you want to provide your own pre-configured instance.

    Note: You cannot provide both axiosInstance and config simultaneously.