node.jsgoogle-mapsclient-library

Using the node.js google maps client library


I think this has to do with my limited experience with javascript. I am using the node.js client library by Google , found here - https://github.com/googlemaps/google-maps-services-js The example shows how to create a client object

var googleMapsClient = require('@google/maps').createClient({
  key: 'your API key here'
});  

And then how to run a gecode request and print out the results :

// Geocode an address.
googleMapsClient.geocode({
  address: '1600 Amphitheatre Parkway, Mountain View, CA'
}, function(err, response) {
  if (!err) {
    console.log(response.json.results);
  }
}); 

What I need to do is read a list of addresses from a file and build an array of objects for all of them .

I want my code to do something along the lines of :

create address-objects array 
create a client object 
open the text files 
for each line in text files
 geocode the line(address)
 add the address and the results into an object and add it to the  address-objects

I don't understand whether the googleMapsClient.geocode returns something , if yes how do I access it ? should I set it to some variable along the lines of :

var gc_results = googleMapsClient.geocode(param , ...)

Hope I was clear , thanks in advance Jonathan.


Solution

  • You can access the response inside the callback function.

    So, if you want to have this function to be called for each address, you can first define an empty array:

    var gc_results = [];
    

    Then you shall call the function for each address you get out of the file, something similar to this:

    addresses.forEach(function(){
       googleMapsClient.geocode({
          address: 
        }, function(err, res) {
          gc_results.push(res.json.results);
      })
    })
    

    after this, you will have the gc_results array full with the information you need