This code uses the Google Maps Places API to find places near a given location or by name, returning a list of matching results.
npm run import -- "use places nearby API"var util = require('util');
var request = util.promisify(require('request'));
var API_KEY = 'AIzaSyDVoQW6NTPuVz8ClOtl0ShITBr_E2sP4l0';
function placesNearby(name, nearby) {
console.log('searching ' + name);
if(typeof nearby === 'undefined') {
const uri = 'https://maps.googleapis.com/maps/api/place/textsearch/json'
+ '?query=' + encodeURIComponent(name)
+ '&key=' + API_KEY;
return request(uri)
.then(r => JSON.parse(r.body).results)
}
const uri = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json'
+ '?name=' + encodeURIComponent(name)
+ '&location=' + nearby.lat + ',' + (nearby.lng || nearby.lon)
+ '&rankby=distance&key=' + API_KEY;
return request(uri)
.then(r => JSON.parse(r.body).results)
}
module.exports = placesNearby;
if(typeof $ !== 'undefined') {
$.async();
var results;
//placesNearby('Kazimierz World Wine Bar near', {lat: 33.505033, lng: -111.926218})
//placesNearby('Rock Springs', lat_long)
placesNearby('Sportsman\'s Bar & Grill near 1000 N Humphreys St, Flagstaff')
.then(r => {
console.log(r);
results = r;
return placeDetails(r[0].place_id);
})
.then(r => {
Object.assign(results[0], r);
return results;
})
.then(r => $.sendResult(r))
.catch(e => $.sendError(e));
}
// Import the required modules and promisify the request function
const axios = require('axios');
const API_KEY = 'AIzaSyDVoQW6NTPuVz8ClOtl0ShITBr_E2sP4l0';
/**
* Perform a text search or a nearby search for places
* @param {string} name - The name of the place to search for
* @param {Object} [options] - Options for the search
* @param {number} [options.lat] - The latitude of the location
* @param {number} [options.lng] - The longitude of the location
* @returns {Promise} A promise that resolves to an array of place results
*/
async function placesNearby(name, options = {}) {
// Log the search query
globalThis.console.info(`Searching for '${name}'`);
// Construct the API URL
const baseUri = 'https://maps.googleapis.com/maps/api/place/';
// Determine whether to perform a text search or a nearby search
const isNearby = Object.keys(options).some(key => ['lat', 'lng'].includes(key));
// Construct the API endpoint and query parameters
const endpoint = isNearby? 'nearbysearch' : 'textsearch';
const query = isNearby
? `?name=${encodeURIComponent(name)}&location=${options.lat},${options.lng}&rankby=distance&key=${API_KEY}`
: `?query=${encodeURIComponent(name)}&key=${API_KEY}`;
try {
// Perform the API request
const response = await axios.get(`${baseUri}${endpoint}/json${query}`);
// Return the results
return response.data.results;
} catch (error) {
// Log any errors that occur
globalThis.console.error(`Error performing search: ${error.message}`);
throw error;
}
}
// Export the placesNearby function
module.exports = placesNearby;
// If this is a browser environment, perform the search and pass the results to the sendResult function
if (typeof $!== 'undefined') {
$().then(() => {
placesNearby('Kazimierz World Wine Bar near', { lat: 33.505033, lng: -111.926218 })
.then(results => {
// Perform a details search on the first result
return placeDetails(results[0].place_id);
})
.then(details => {
// Update the first result with the details
results[0].details = details;
// Send the updated results to the server
return $().sendResult(results);
})
.catch(error => {
// Send any errors to the server
return $().sendError(error);
});
});
}
// TODO: Implement a placeDetails function to fetch additional details about a place
async function placeDetails(placeId) {
// TODO: Implement the placeDetails function using the Google Maps Places API
} This code snippet searches for places near a given location using the Google Maps Places API.
Here's a breakdown:
Dependencies:
request module for making HTTP requests and uses util.promisify to convert it to a Promise-based API.API Key:
placesNearby Function:
name (the place to search for) and an optional nearby object (containing latitude and longitude coordinates) as input.nearby is provided, it constructs a URL for the nearbysearch endpoint, specifying the name, location, and ranking by distance.textsearch endpoint, searching for the name directly.request, parses the JSON response, and returns an array of matching places.Module Export:
placesNearby function is exported as a module, making it available for use in other parts of the application.Execution Block:
$ object is available (likely a testing framework).placesNearby with a sample query and then chains additional calls to placeDetails (not shown in the provided code) to retrieve more detailed information about the first matching place.Purpose:
This code snippet demonstrates how to use the Google Maps Places API to search for places near a given location and retrieve basic information about the results.