This will almost certainly be something super basic but I cannot for the life of me work out what's wrong. I have a data object coming back from Google Maps JS API
{
"destination_addresses" : [ "12 Ansell Rd, London SW17, UK" ],
"origin_addresses" : [
"911 Alfreds Way, Barking IG11 0AX, UK",
"911 Alfreds Way, Barking IG11 0AX, UK",
"50 Buttesland St, Hoxton, London N1 6BY, UK"
],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "24.4 km",
"value" : 24411
},
"duration" : {
"text" : "55 mins",
"value" : 3297
},
"duration_in_traffic" : {
"text" : "58 mins",
"value" : 3454
},
"status" : "OK"
}
]
},
{
"elements" : [
{
"distance" : {
"text" : "24.4 km",
"value" : 24411
},
"duration" : {
"text" : "55 mins",
"value" : 3297
},
"duration_in_traffic" : {
"text" : "58 mins",
"value" : 3454
},
"status" : "OK"
}
]
},
{
"elements" : [
{
"distance" : {
"text" : "13.9 km",
"value" : 13905
},
"duration" : {
"text" : "48 mins",
"value" : 2909
},
"duration_in_traffic" : {
"text" : "45 mins",
"value" : 2717
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I'm retrieving this using .get with require's https module and it works absolutely fine and then I print the data like so...
https.get(`https://maps.googleapis.com/maps/api/distancematrix/json?origins=51.5285,0.0847|51.5285,0.0847|51.5285,-0.0847&destinations=51.432622,-0.164496&departure_time=now&key=APIKEY`, (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
//When all data is received
resp.on('end', () => {
console.log(data);
});
});
The problem is as soon as I try to access (even just console log) any data in the object like
data.destination_addresses
it returns undefined. I thought this might be to do with asynchronous issues but it doesn't make sense that I can print the data variable but not it's attributes individually
You will need parse it as JSON first
var obj = JSON.parse(data);
console.log(obj.destination_addresses);