Hey, I’ve recently used OpenRouteService API for Distance Matrix.
But now that the matrix shows in my output on VSCode, I don’t know how to parse the returned JSON.
By that, I don’t know what is the name I have to put in.
let XMLHttpRequest = require('xhr2');
let request = new XMLHttpRequest();
request.open('POST', "https://api.openrouteservice.org/v2/matrix/foot-walking");
request.setRequestHeader('Accept', 'application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8');
request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Authorization', 'xyz');
request.onreadystatechange = function () {
if (this.readyState === 4) {
console.log('Status:', this.status);
console.log('Headers:', this.getAllResponseHeaders());
console.log('Body:', this.responseText);
}
};
const body = '{"locations":[[2.3556456565856934,48.787715911865234],[2.3691248893737793,48.79338073730469],[2.3862559,48.7928631]],"id":"matrix","metrics":["distance","duration"]}';
request.send(body);
const obj = JSON.parse();
It seems to work since there’s no error but I have another problem now.
const body = '{"locations":[[2.3556456565856934,48.787715911865234],[2.3691248893737793,48.79338073730469],[2.3862559,48.7928631]],"id":"matrix","metrics":["distance","duration"]}';
request.send(body);
const obj = JSON.parse(request.response);
console.log(obj[durations]);
This returns me this error : durations is not defined.
And when i just type console.log(obj);
It just returns null before anything has happened.
I’m new to JS as I said, but I assume it is because, in some sort of way, console.log occurs before anything else in the code, thus making obj null or durations not defined.
Is there a way to fix that ?
Or is the problem somewher else ?
P.S. : the first lines of the code remained unchanged.
Try JSON.stringify when logging objects to console. Objects are not displayed in console. console.log(JSON.stringify(obj));
or just log request.response directly.
Maybe try out our JavaScript package which handles a lot of the request parts and makes it a bit simpler to call our API via JS.