Hello I'm trying to read JSON data from an api but it doesn't work when I try to get data from that api works fine and when I try to get the distance value I get undefined.Please help
The code
fetch('https://maps.googleapis.com/maps/api/distancematrix/json?units=meter&origins=Gurd%20Shola%201%20Station,%20Addis%20Ababa&destinations=Bole%20Medhane%20Alem%20Church,%20Addis%20Ababa&key=API_KEY')
.then(response => {
return response.json()
})
.then(data => {
// Work with JSON data here
console.log(data.rows.elements.distance.value)
})
.catch(err => {
})
the result from the web is just like this
{
"destination_addresses" : [ "Addis Ababa, Ethiopia" ],
"origin_addresses" : [ "Addis Ababa, Ethiopia" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "6.4 km",
"value" : 6386
},
"duration" : {
"text" : "15 mins",
"value" : 901
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
Change data.rows.elementes.distance.value
to data.rows[0].elements[0].distance.value
..
Check for typo here it is elements
and not elementes
..
Also rows
and elements
is an array and if you need to get the distance then you need to get it like rows[0].elements[0].distance
..
const data = { "destination_addresses" : [ "Addis Ababa, Ethiopia" ], "origin_addresses" : [ "Addis Ababa, Ethiopia" ], "rows" : [ { "elements" : [ { "distance" : { "text" : "6.4 km", "value" : 6386 }, "duration" : { "text" : "15 mins", "value" : 901 }, "status" : "OK" } ] } ], "status" : "OK" } console.log(data.rows[0].elements[0].distance);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.