3

I'm using a npm package called request to make a http request to https://maps.googleapis.com/maps/api/geocode/json?address=Jur%C4%8Dkova+cesta+225&key=AIzaSyChkPdCaAaVZwYof8ZbKspokuYt41NlJ_0

Now I want to parse the data I receive in order to extract the LAT/LONG and write it into my database. But so far all I get as output to console is:

[ { address_components:
     [ [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object] ],
    formatted_address: 'Breznikova ulica 15, 1230 Domžale, Slovenia',
    geometry:
     { location: [Object],
       location_type: 'ROOFTOP',
       viewport: [Object] },
    place_id: 'ChIJR2mtdUc0ZUcRv5nXK0zEx7M',
    types: [ 'street_address' ] },
  { address_components:
     [ [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object] ],
    formatted_address: 'Breznikova ulica 15, 1000 Ljubljana, Slovenia',
    geometry:
     { location: [Object],
       location_type: 'ROOFTOP',
       viewport: [Object] },
    place_id: 'ChIJ19Ax9OPMekcRoPvkJ6SKNEg',
    types: [ 'street_address' ] },
  { address_components:
     [ [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object] ],
    formatted_address: 'Breznikova ulica 15, 2000 Maribor, Slovenia',
    geometry:
     { location: [Object],
       location_type: 'ROOFTOP',
       viewport: [Object] },
    place_id: 'ChIJDUicXFd2b0cRYrf99vgTPBs',
    types: [ 'street_address' ] } ]

here's the extract of my code that produces this from my server.js file:

//get lat and long before saving from gmaps API
//build gmaps API URL
var urlAddress = shop.address.replace(/ /gi, '+');
var urlAPIKey = '&key=AIzaSyChkPdCaAaVZwYof8ZbKspokuYt41NlJ_0';
var url = 'https://maps.googleapis.com/maps/api/geocode/json?address=';
url = url.concat(urlAddress).concat(urlAPIKey);
//make a request
request({
    uri: url,
    method:"GET",
    timeout: 100000
    }, function(error, response, body) {
        var gmaps = JSON.parse(body);
        console.log(gmaps.results);
});

if anyone can point out what I'm doing wrong that would be great. If I try to output the object it just returns undefined.

Miha Šušteršič
  • 9,742
  • 25
  • 92
  • 163

1 Answers1

2

The reason why it appears as [Object] is for readability, if you want to show a full dump of the results, you have to pass it through JSON.stringify first.

As to access the address_components, the results is an array, so you'll have to access them for a specific element of that array (e.g. gmaps.results[0].address_components)

ploutch
  • 1,204
  • 10
  • 12