Google Maps API (Node.js)

JS
S
JavaScript

Ready to use snippet of how to query for Google Places IDs using the official Google Maps API from NPM.

1import googleMapsApi from '@google/maps';
2import Promise from 'bluebird';
3
4class GooglePlacesService {
5  constructor() {
6    this.client = googleMapsApi.createClient({
7      key: process.env.GOOGLE_MAPS_KEY
8    });
9  }
10
11  getGooglePlaceIdFromName(name, location) {
12    return new Promise((resolve, reject) => {
13      const request = {
14        input: name,
15        inputtype: 'textquery',
16        locationbias: location ? `point:${location.lon},${location.lat}`: undefined
17      };
18      this.client.findPlace(request, (err, response) => {
19        if(err) return reject(err);
20        const candidate = (response.json.candidates && response.json.candidates.length > 0) ? response.json.candidates[0] : undefined;
21        return resolve(candidate && candidate.place_id ? candidate.place_id : undefined);
22      });
23    })
24  };
25}
26
27// singleton
28export default new GooglePlacesService();

Created on 2/28/2019