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")
{ 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'
}
JSON.parse(response.body);
JSON.stringify(response.body.results[2]);
TypeError: Cannot read property '2' of undefined
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));
undefined
^ SyntaxError: Unexpected token u in JSON at position 0
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);