google maps | use places nearby API | use Google Geocaching | Search

The code provides a function called placeDetails that retrieves detailed information about a Google Places location using its ID and your Google Maps API key. It utilizes the request library to make an API call and returns the parsed JSON response containing place details.

Run example

npm run import -- "place details google maps"

place details google maps

var util = require('util');
var request = util.promisify(require('request'));

var API_KEY = 'AIzaSyDVoQW6NTPuVz8ClOtl0ShITBr_E2sP4l0';

function placeDetails(placeId) {
    const uri = 'https://maps.googleapis.com/maps/api/place/details/json' 
        + '?placeid=' + placeId
        + '&key=' + API_KEY;
    return request(uri)
        .then(r => JSON.parse(r.body).result)
}
module.exports = placeDetails;

What the code could have been:

// Import required modules and functions
const { promisify } = require('util');
const request = require('request');
const logger = require('loglevel'); // Adding a logger for better error handling

// Load API key from environment variables
const API_KEY = process.env.GOOGLE_MAPS_API_KEY;

// Define a function to get place details
function getPlaceDetails(placeId) {
    /**
     * Retrieves place details from Google Maps API
     * @param {string} placeId - Unique identifier for the place
     * @returns {Promise} A promise resolving to the place details
     */
    const URI = 'https://maps.googleapis.com/maps/api/place/details/json'; // Using a constant for the base URL
    const params = {
        placeid: placeId,
        key: API_KEY,
    };

    // Construct the full URI with query parameters
    const fullURI = `${URI}?${Object.keys(params).map((key) => `${key}=${params[key]}`).join('&')}`;

    // Send a GET request to the API
    return new Promise((resolve, reject) => {
        request.get(fullURI, (error, response, body) => {
            if (error) {
                // Log and reject the error
                logger.error(`Error fetching place details: ${error}`);
                reject(error);
            } else if (response.statusCode!== 200) {
                // Log and reject non-200 status codes
                logger.error(`Non-200 status code: ${response.statusCode}`);
                reject(new Error(`Non-200 status code: ${response.statusCode}`));
            } else {
                // Parse the response body as JSON
                const data = JSON.parse(body);
                resolve(data.result);
            }
        });
    });
}

// Export the function as a module
module.exports = getPlaceDetails;

This code defines a function called placeDetails that fetches detailed information about a Google Places location given its ID.

Here's a breakdown:

  1. Dependencies:

    • util: A built-in Node.js module for utility functions.
    • request: A library for making HTTP requests, promisified using util.promisify for easier asynchronous handling.
  2. API Key:

    • API_KEY: Stores your Google Maps API key, which is required for making requests to the Google Places API.
  3. placeDetails Function:

    • Takes a placeId (a unique identifier for a Google Places location) as input.
    • Constructs a URL to the Google Places Details API endpoint, including the placeId and your API key.
    • Uses request to make a GET request to the constructed URL.
    • Parses the JSON response and returns the result object containing detailed information about the place.
  4. Export:

    • The placeDetails function is exported using module.exports, making it available for use in other parts of your application.

Let me know if you have any other code snippets you'd like me to explain!