0

I have a following code where I want to store the place_id in a variable outside googleMapsClient? But I don't get the desired value.

// Create client with a Promise constructor
const googleMapsClient = require('@google/maps').createClient({
  key: 'KEY',
  Promise: Promise // 'Promise' is the native constructor.
});

var place_id;

place_id = function () {

 return googleMapsClient.places({
  query: '1600 Amphitheatre Parkway, Mountain View, CA'
}).asPromise()
  .then((response) => {
    place_id = response.json.results[0].place_id;
  })
  .catch((err) => {
    place_id = err;
  });
};

console.dir(place_id);

Output:

[Function: place_id]

Can anyone help me with this?

1 Answers1

0

This has nothing to do with Maps. I suggest you familiarise youself with the difference between a function and a function expression in Node.js.

In your program place_id is a function expression, and what you are seeing with the output of console.dir() is correct for a function expression. I think you need to assign the result of the function (invoked through the function expression) as per the example below:

var place_id = function () {
    return "Hello World";
};
console.log(place_id);
console.dir(place_id);
var s = place_id();
console.log(s);

Output:

[Function: place_id]
[Function: place_id]
Hello World
P Burke
  • 1,630
  • 2
  • 17
  • 31
  • Thank you for your answer. Now, I get Promise { }. Actually, I am struggling to set the place_id out of google map client. I want to use it to construct the URL to the map. I started using Node.js yesterday, so please pardon my ignorance. Any references to documentation and/or tutorials are highyl appreciated. – user8910298 Jan 17 '19 at 14:35
  • Starting Node.js using the Google Maps API with promises is definitely jumping into the deep end. [This](https://github.com/googlemaps/google-maps-services-js/blob/master/spec/e2e/directions-spec.js) appears to have some MAPS with promises examples, but I would recommend you spend a few days just getting to grips with Node.js first. Try [stackoverflow](https://stackoverflow.com/questions/2353818/how-do-i-get-started-with-node-js) – P Burke Jan 17 '19 at 14:59
  • Thanks for the links. I will go through those and try to understand my problem. – user8910298 Jan 17 '19 at 15:06