Convert Figma logo to code with AI

googlemaps logogoogle-maps-services-js

Node.js client library for Google Maps API Web Services

2,890
639
2,890
40

Top Related Projects

41,217

πŸƒ JavaScript library for mobile-friendly interactive maps πŸ‡ΊπŸ‡¦

OpenLayers

A lightweight set of tools for working with ArcGIS services in Leaflet. :rocket:

React.js Google Maps integration component

12,182

WebGL2 powered visualization framework

Quick Overview

The google-maps-services-js repository is a Node.js client library for Google Maps API Web Services. It provides a simple and efficient way to interact with various Google Maps APIs, including Directions, Distance Matrix, Elevation, Geocoding, Time Zone, and Places APIs.

Pros

  • Easy integration with Node.js applications
  • Supports both Promise-based and callback-based programming styles
  • Comprehensive coverage of Google Maps API Web Services
  • Well-documented and actively maintained

Cons

  • Requires a Google Cloud Platform API key or client ID
  • Rate limiting and usage restrictions based on Google Maps API policies
  • Limited to server-side usage (not suitable for client-side browser applications)
  • Dependency on Google's services and potential future API changes

Code Examples

  1. Geocoding an address:
const { Client } = require("@googlemaps/google-maps-services-js");

const client = new Client({});

client
  .geocode({
    params: {
      address: "1600 Amphitheatre Parkway, Mountain View, CA",
      key: "YOUR_API_KEY",
    },
  })
  .then((r) => {
    console.log(r.data.results[0].geometry.location);
  })
  .catch((e) => {
    console.log(e.response.data.error_message);
  });
  1. Calculating distance between two points:
const { Client } = require("@googlemaps/google-maps-services-js");

const client = new Client({});

client
  .distancematrix({
    params: {
      origins: ["Washington, DC"],
      destinations: ["New York City, NY"],
      key: "YOUR_API_KEY",
    },
  })
  .then((r) => {
    console.log(r.data.rows[0].elements[0].distance.text);
  })
  .catch((e) => {
    console.log(e.response.data.error_message);
  });
  1. Finding nearby places:
const { Client } = require("@googlemaps/google-maps-services-js");

const client = new Client({});

client
  .placesNearby({
    params: {
      location: { lat: 40.7128, lng: -74.0060 },
      radius: 1000,
      type: "restaurant",
      key: "YOUR_API_KEY",
    },
  })
  .then((r) => {
    console.log(r.data.results);
  })
  .catch((e) => {
    console.log(e.response.data.error_message);
  });

Getting Started

  1. Install the library:

    npm install @googlemaps/google-maps-services-js
    
  2. Import the Client class and create an instance:

    const { Client } = require("@googlemaps/google-maps-services-js");
    const client = new Client({});
    
  3. Use the client to make API calls, providing your API key:

    client
      .elevation({
        params: {
          locations: [{ lat: 45.5, lng: -122.7 }],
          key: "YOUR_API_KEY",
        },
      })
      .then((r) => {
        console.log(r.data.results[0].elevation);
      })
      .catch((e) => {
        console.log(e.response.data.error_message);
      });
    

Competitor Comparisons

41,217

πŸƒ JavaScript library for mobile-friendly interactive maps πŸ‡ΊπŸ‡¦

Pros of Leaflet

  • Open-source and lightweight, making it more flexible and customizable
  • Supports a wide range of map providers, not limited to Google Maps
  • Large community and extensive plugin ecosystem

Cons of Leaflet

  • Less comprehensive documentation compared to Google Maps
  • Fewer built-in features, requiring more custom implementation
  • May require additional plugins for advanced functionality

Code Comparison

Leaflet:

var map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: 'Β© OpenStreetMap contributors'
}).addTo(map);

google-maps-services-js:

const client = new Client({});
client.elevation({
    params: {
        locations: [{lat: 45, lng: -110}],
        key: 'YOUR_API_KEY'
    }
})
.then(r => console.log(r.data.results[0].elevation));

The Leaflet code focuses on map initialization and tile layer setup, while google-maps-services-js demonstrates API interaction for elevation data. Leaflet's approach is more front-end oriented, whereas google-maps-services-js is designed for server-side use with Google Maps APIs.

OpenLayers

Pros of OpenLayers

  • Open-source and free to use without restrictions
  • Supports a wide range of data formats and sources
  • Highly customizable with extensive API and plugin ecosystem

Cons of OpenLayers

  • Steeper learning curve compared to Google Maps
  • Less comprehensive documentation and community support
  • May require more setup and configuration for basic use cases

Code Comparison

OpenLayers:

import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';

const map = new Map({
  target: 'map',
  layers: [new TileLayer({ source: new OSM() })],
  view: new View({ center: [0, 0], zoom: 2 })
});

google-maps-services-js:

const { Client } = require("@googlemaps/google-maps-services-js");

const client = new Client({});
client
  .elevation({
    params: { locations: [{ lat: 45, lng: -110 }], key: "YOUR_API_KEY" },
    timeout: 1000
  })
  .then(r => console.log(r.data.results[0].elevation))
  .catch(e => console.log(e));

OpenLayers focuses on client-side map rendering, while google-maps-services-js is primarily for server-side API interactions. OpenLayers offers more flexibility for custom map implementations, whereas google-maps-services-js provides easier access to Google Maps services and data.

A lightweight set of tools for working with ArcGIS services in Leaflet. :rocket:

Pros of esri-leaflet

  • Integrates seamlessly with Leaflet, a popular open-source mapping library
  • Provides access to Esri's extensive collection of basemaps and data layers
  • Offers a more lightweight solution for web mapping applications

Cons of esri-leaflet

  • Limited to Esri's ecosystem, which may not be as versatile as Google Maps
  • Requires an ArcGIS Online account for some features, potentially increasing costs
  • May have a steeper learning curve for developers unfamiliar with Esri products

Code Comparison

esri-leaflet:

const map = L.map('map').setView([51.505, -0.09], 13);
L.esri.basemapLayer('Streets').addTo(map);
L.esri.featureLayer({url: 'https://services.arcgis.com/....'}).addTo(map);

google-maps-services-js:

const client = new Client({});
client.elevation({
  params: {
    locations: [{lat: 45, lng: -110}],
    key: 'YOUR_API_KEY'
  }
}).then(r => console.log(r.data.results[0].elevation));

Both libraries offer straightforward ways to create maps and access geospatial services, but they cater to different ecosystems and use cases. esri-leaflet is more focused on web mapping with Esri data, while google-maps-services-js provides a broader range of Google Maps API services.

React.js Google Maps integration component

Pros of react-google-maps

  • Specifically designed for React applications, providing React components for easy integration
  • Offers a higher level of abstraction, simplifying the process of adding Google Maps to React projects
  • Includes additional features like drawing tools and custom overlays out of the box

Cons of react-google-maps

  • Less flexible for non-React projects or when more direct control over the Google Maps API is needed
  • May have a steeper learning curve for developers not familiar with React concepts
  • Potentially larger bundle size due to React dependencies

Code Comparison

react-google-maps:

import { GoogleMap, Marker } from "react-google-maps"

const MyMapComponent = withGoogleMap((props) =>
  <GoogleMap defaultZoom={8} defaultCenter={{ lat: -34.397, lng: 150.644 }}>
    <Marker position={{ lat: -34.397, lng: 150.644 }} />
  </GoogleMap>
)

google-maps-services-js:

const client = new Client({});
client
  .elevation({
    params: {
      locations: [{ lat: 45, lng: -110 }],
      key: "YOUR_API_KEY",
    },
    timeout: 1000,
  })
  .then((r) => {
    console.log(r.data.results[0].elevation);
  })
  .catch((e) => {
    console.log(e.response.data.error_message);
  });
12,182

WebGL2 powered visualization framework

Pros of deck.gl

  • Highly performant for rendering large datasets and complex visualizations
  • Supports a wide range of 2D and 3D data visualization layers
  • Integrates well with React and other web frameworks

Cons of deck.gl

  • Steeper learning curve due to its extensive API and capabilities
  • May be overkill for simple mapping needs or small datasets
  • Requires more setup and configuration compared to Google Maps Services

Code Comparison

deck.gl example:

import DeckGL from '@deck.gl/react';
import {ScatterplotLayer} from '@deck.gl/layers';

const App = ({data, viewport}) => (
  <DeckGL layers={[new ScatterplotLayer({data})]} initialViewState={viewport} />
);

Google Maps Services JS example:

const client = new Client({});
client
  .elevation({params: {locations: [{lat: 45, lng: -110}], key: 'YOUR_API_KEY'}})
  .then((r) => {
    console.log(r.data.results[0].elevation);
  })
  .catch((e) => {
    console.log(e);
  });

Summary

deck.gl is a powerful data visualization library for creating complex, high-performance map visualizations, while Google Maps Services JS focuses on providing easy access to Google Maps APIs for various mapping services. deck.gl offers more flexibility and advanced rendering capabilities but requires more setup and expertise. Google Maps Services JS is simpler to use for basic mapping needs and integrates seamlessly with Google's ecosystem.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Node.js Client for Google Maps Services

npm Test Release codecov GitHub contributors semantic-release Discord

This library is a refactor of a previous version published to @google/maps. It is now being published to @googlemaps/google-maps-services-js.

Use Node.js? Want to geocode something? Looking for directions? This library brings the Google Maps API Web Services to your Node.js application.

The Node.js Client for Google Maps Services is a Node.js Client library for the following Google Maps APIs:

Keep in mind that the same terms and conditions apply to usage of the APIs when they're accessed through this library.

Attention!

This library is designed for server-side Node.js applications. Attempting to use it client-side, in either the browser or any other environment like React Native, may in some cases work, but mostly will not. Please refrain from reporting issues with these environments when attempting to use them, since server-side Node.js applications is the only supported environment for this library. For other environments, try the Maps JavaScript API, which contains a comparable feature set, and is explicitly intended for use with client-side JavaScript.

Quick Start

$ npm install @googlemaps/google-maps-services-js

Below is a simple example calling the elevation method on the client class.

Import the Google Maps Client using TypeScript and ES6 module:

import {Client} from "@googlemaps/google-maps-services-js";

Alternatively using JavaScript without ES6 module support:

const {Client} = require("@googlemaps/google-maps-services-js");

Now instantiate the client to make a call to one of the APIs.

const client = new Client({});

client
  .elevation({
    params: {
      locations: [{ lat: 45, lng: -110 }],
      key: process.env.GOOGLE_MAPS_API_KEY,
    },
    timeout: 1000, // milliseconds
  })
  .then((r) => {
    console.log(r.data.results[0].elevation);
  })
  .catch((e) => {
    console.log(e.response.data.error_message);
  });

Reference Documentation

The generated reference documentation can be found here. The TypeScript types are the authoritative documentation for this library and may differ slightly from the descriptions.

Developing

In order to run the end-to-end tests, you'll need to supply your API key via an environment variable.

$ export GOOGLE_MAPS_API_KEY=AIza-your-api-key
$ npm test

Migration

This section discusses the migration from @google/maps to @googlemaps/google-maps-services-js and the differences between the two.

Note: The two libraries do not share any methods or interfaces.

The primary difference is @google/maps exposes a public method that takes individual parameters as arguments while @googlemaps/google-maps-services-js exposes methods that take params, headers, body, instance(see Axios). This allows direct access to the transport layer without the complexity that was inherent in the old library. Below are two examples.

Old (@google/maps):

const googleMapsClient = require('@google/maps').createClient({
  key: 'your API key here'
});

googleMapsClient
  .elevation({
    locations: {lat: 45, lng: -110}
  })
  .asPromise()
  .then(function(r) {
    console.log(r.json.results[0].elevation);
  })
  .catch(e => {
  console.log(e);
  });

New (@googlemaps/google-maps-services-js):

const client = new Client({});

client
  .elevation({
    params: {
      locations: [{ lat: 45, lng: -110 }],
      key: process.env.GOOGLE_MAPS_API_KEY
    },
    timeout: 1000 // milliseconds
  }, axiosInstance)
  .then(r => {
    console.log(r.data.results[0].elevation);
  })
  .catch(e => {
    console.log(e);
  });

The primary differences are in the following table.

OldNew
Can provide paramsCan provide params, headers, instance, timeout (see Axios Request Config)
API key configured at ClientAPI key configured per method in params object
Retry is supportedRetry is configurable via axios-retry or retry-axios
Does not use promises by defaultPromises are default
Typings are in @types/googlemapsTypings are included
Does not support keep aliveSupports keep alive
Does not support interceptorsSupports interceptors
Does not support cancelalationSupports cancellation

Premium Plan Authentication

Authentication via client ID and URL signing secret is provided to support legacy applications that use the Google Maps Platform Premium Plan. The Google Maps Platform Premium Plan is no longer available for sign up or new customers. All new applications must use API keys.

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 // milliseconds
  })
  .then(r => {
    console.log(r.data.results[0].elevation);
  })
  .catch(e => {
    console.log(e.response.data.error_message);
  });

Support

This library is community supported. We're comfortable enough with the stability and features of the library that we want you to build real production applications on it. We will try to support, through Stack Overflow, the public surface of the library and maintain backwards compatibility in the future; however, while the library is in version 0.x, we reserve the right to make backwards-incompatible changes. If we do remove some functionality (typically because better functionality exists or if the feature proved infeasible), our intention is to deprecate and give developers a year to update their code.

If you find a bug, or have a feature suggestion, please log an issue. If you'd like to contribute, please read How to Contribute.

NPM DownloadsLast 30 Days