In practice, Google Maps API is not directly installed via npm. Typically, to use Google Maps API, you need to include Google's JavaScript library in your web page. However, if you want to conveniently manage Google Maps-related functionalities in Node.js projects, you can use third-party npm packages that wrap these features.
Here is a common example of how to install and use Google Maps via npm:
Step 1: Choose an appropriate npm package
For Google Maps functionalities, multiple third-party npm packages are available, such as google-maps-api-loader, @googlemaps/google-maps-services-js, etc. Here, we use @googlemaps/google-maps-services-js as an example, which is an officially supported Node.js client library for accessing Maps Web services.
Step 2: Install the npm package
In the root directory of your Node.js project, open the terminal or command line tool, and run the following command to install:
bashnpm install @googlemaps/google-maps-services-js
Step 3: Use the API
After installing the package, you can use Google Maps API as follows:
javascriptconst {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 // Optional: Set request timeout }) .then(r => { console.log(r.data.results[0].elevation); }) .catch(e => { console.log(e.response.data.error_message); });
Notes:
- API Key: In the above code,
YOUR_API_KEYneeds to be replaced with a valid API key obtained from Google Cloud Platform. - Security: Ensure that you do not expose your API key in public code repositories.
Using this approach, you can efficiently integrate and use various Google Maps services in your Node.js projects, rather than loading the JavaScript library directly in the frontend via <script> tags. This helps improve the modularity and security of your project.