Dringo Dringo - 4 years ago 82
Javascript Question

Google maps Geocode results undefined

So I am trying to geocode an address from google maps but when I try to access the results it says the array containing the results are undefined. I've have done the exact opposite of this with looking up an address from coordinates, granted that was in PHP, I'm not sure why this isn't working. I would like to just parse through the JSON to get to the data I want (The Lat and long), but since I am unable to do that, I have done a work around and just did JSON.stringify and locate the Lat & long via

str.locate("lat")
.

However, When I parse the json response from google maps I get this

{ results:
[ { address_components: [Object],
formatted_address: '2985 NW Moda Way, Hillsboro, OR 97124, USA',
geometry: [Object],
place_id: 'ChIJt-G-MmcPlVQROzDAlEVj1nA',
types: [Object] } ],
status: 'OK'
}


Where the object inside the geometry is what I want, to get this I am using the request library from node.js. And I am console logging the
JSON.parse(response.body);
to get the results array but trying to get to the results object via

JSON.stringify(response.body.results[2]);
results in
TypeError: Cannot read property '2' of undefined


Edit: Code I am using request for google maps API

request('https://maps.googleapis.com/maps/api/geocode/json?address=' + address + '+' + parsedStreet + '&key=' + key, function(err, response) {
if (err)
console.log("holy shit error");
console.log(JSON.parse(response.body.results));


which returns

undefined
^ SyntaxError: Unexpected token u in JSON at position 0


address and parsedStreet are address values that I am reading from a file to convert into coordinates

Answer Source

It looks like you're trying to access the result index before you actually parse the JSON into an object, so you're trying to get the result index from a string. You need to JSON.parse just the response body, and then get into the results, like so:

console.log(JSON.parse(response.body).results);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download