Showing directions output as leaflet geoJson layer

Hi,
I was looking at the documentation for https://openrouteservice.org/dev/#/api-docs/directions/get and on that page you also show the response of the API on a map by using the leaflet library. I am trying to do the same thing, but don’t know how to get from the response of the directions API to the map. The API documentation says the response is in geoJson format, but just putting the response (body) into a leaflet L.geoJSON(response).addTo(map); gets me a “Error: Invalid GeoJSON object.” Any help on how to work the API response into leaflet would be much appreciated.
Thanks,
Anton

The directions response is by default encodedpolyline (as per our docs).

If you specifiy format=geojson, you get a GeoJSON response.

Thank you, that helped a lot.

The main description for get directions in the docs reads: “Returns a route between two or more locations for a selected profile and its settings as GeoJSON response.” … maybe that should be changed to avoid confusion.

Best wishes,
Anton

Hi,

I’m having the same problem as above (“Error: Invalid GeoJSON object”). Where can i insert the statement “format=geojson” ?

Thanks!

let request = new XMLHttpRequest();

request.open(‘POST’, “https://api.openrouteservice.org/v2/directions/driving-hgv/json”);

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’, ‘---------------------------’);

request.onreadystatechange = function () {
if (this.readyState === 4) {
console.log(‘Status:’, this.status);
console.log(‘Headers:’, this.getAllResponseHeaders());
console.log(‘Body:’, this.responseText);
}
};

const body = ‘{“coordinates”:[[8.889055,44.418111],[8.944448,44.404032]],“attributes”:[“detourfactor”,“percentage”],“extra_info”:[“steepness”,“waytype”,“surface”],“instructions”:“true”,“format”:“geoJSON”,“language”:“it”,“options”:{“avoid_polygons”:{“type”:“Polygon”,“coordinates”:[[[“8.90115”,“44.41618”],[“8.92476”,“44.42204”],[“8.91875”,“44.40594”],[“8.90115”,“44.41618”]]]},“vehicle_type”:“hgv”},“preference”:“fastest”,“units”:“km”,“geometry”:“true”}’;

request.send(body);

alert(body);

L.geoJSON(body).addTo(map);

Change the URL. And read the docs;)

https://api.openrouteservice.org/v2/directions/driving-hgv/geojson

https://openrouteservice.org/dev/#/api-docs/v2/directions/{profile}/geojson/post

Sorry, but that was not helpful to me.

I’m having the same problem and I have a different URL.
request.open(‘POST’, “https://api.openrouteservice.org/v2/directions/driving-car/geojson”);

Is it even possible to just print it to the map with just
L.geoJSON(body).addTo(map);

Then it’s best if you explain what’s not working for you, i.e. the exact request incl POST parameters and headers and the response.

This the code I have so far. I tried a bunch of different variables for ??? but nothing worked. I also couldn`t find an example on how to show the route in leaflet anywhere.

let request = new XMLHttpRequest();

request.open('POST', "https://api.openrouteservice.org/v2/directions/driving-hgv/geojson");

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', '5b3ce3597851110001cf624867f677852d8b48b5ad3a20d0c1932a8e');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);

  }
};

const body = '{"coordinates":[[11.0419554,49.5939908],[11,49.6],[11.0393399,49.594125]],"attributes":["detourfactor","percentage"]}';

request.send(body);
    L.geoJSON(???).addTo(map);

That’s a very basic programming error. Please use Stack Overflow to resolve.

You’re not referencing the response of the web request anywhere. Refer to XMLHttpRequest documentation. Somewhere you’ll send a request and get back an object, which contains the response (likely .send). Or use some friendlier library like axios.

Hey @Ann,
If you want to use ors with javascript you might want to use our openrouteservice-js it should provide the same functionality you seek and you might find it easier to use.

I would guess you are getting the Console Log for “this.responseText”… so that would need to be parsed as JSON and then included in your L.geoJSON(???).addTo(map);

let request = new XMLHttpRequest();

request.open('POST', "https://api.openrouteservice.org/v2/directions/driving-hgv/geojson");

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', 'API_KEY');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
    var json = JSON.parse(this.responseText)
    L.geoJSON(json).addTo(map);
  }
};

const body = '{"coordinates":[[11.0419554,49.5939908],[11,49.6],[11.0393399,49.594125]],"attributes":["detourfactor","percentage"]}';

request.send(body);

Hello, i would like to display a route in a wordpress maps markers pro. I am using javascipt as a callback, and im trying to configure my api call, but it doesn’t seem to work. I read the docs, but couldn’t find anything useful. Here’s my code:

function myCallback(mmp) {
     var mapsPlaceholder = [];

//-----------------------------------------------------------------------------------------------     
 let request = new XMLHttpRequest();

request.open('POST', "https://api.openrouteservice.org/v2/directions/driving-car/geojson");

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', '--------my api key--------');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

const body = '{"coordinates":[[23.7469,37.9754],[23.7667,37.9683]]}';
request.send(body);

L.geoJSON(body).addTo(mmp);

and the response is:

[Maps Marker Pro] Error loading settings (Error: Invalid GeoJSON object.)

Any help would be appreciated.

Thanks in advance!

you are adding the body constant to the map, not the response

I am now getting this error message: [Maps Marker Pro] Error loading settings (ReferenceError: response is not defined)

with my code being like this:

function myCallback(mmp) {
     var mapsPlaceholder = [];

//-----------------------------------------------------------------------------------------------     
 let request = new XMLHttpRequest();

request.open('POST', "https://api.openrouteservice.org/v2/directions/driving-car/geojson");

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', 'MY API KEY');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

const body = '{"coordinates":[[23.7469,37.9754],[23.7667,37.9683]]};//,"format":"geoJSON"}';
request.send(body);

L.geoJSON(response).addTo(mmp);

Sorry, but this is not really an openrouteservice problem. Our API returns a GeoJSON.
You seem to be lacking some basic understanding of how your code works.

You should probably do some JavaScript tutorials (maybe using the request library) and maybe use an IDE, which would have told you that the variable response is not defined in that context.

If the answer from Showing directions output as leaflet geoJson layer - #11 by richtom80 doesn’t work you could also try reading the documentation of L.geoJSON and the JS request library

or as suggested also previously in this thread
Showing directions output as leaflet geoJson layer - #10 by amandus

Hello. I am trying to use the avoid_polygons feature in javascript, but i can’t seem to make this work. I have done this before in several other programming languages, but doesn’t work in this one.

let request = new XMLHttpRequest();
var flag = 0;

request.open('POST', "https://api.openrouteservice.org/v2/directions/driving-car/geojson");

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', 'ggggggg');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);

   var json = JSON.parse(this.responseText)
    L.geoJSON(json).addTo(map);
}

const body = '{"coordinates":[[cccc],[vvvv]], "options" : {"avoid_polygons" : {"type" : "Polygon","coordinates" : [blah]}}}';
request.send(body);

the error message is about invalid GeoJSON object

Did you double check your GeoJSON polygon then?

yes i have used it as a Geojson object elsewhere. I think the problem is with the body of the API call.

const body = '{"coordinates":[[cccc],[vvvv]], "options" : {"avoid_polygons" : {"type" : "Polygon","coordinates" : [blah]}}}';
const body = '{"coordinates":[[8.681495,49.41461],[8.687872,49.420318]],"options":{"avoid_polygons":{"type":"Polygon","coordinates":[[[8.681516647338867,49.41714356469011],[8.687610626220703,49.41714356469011],[8.687610626220703,49.41745066666471],[8.681516647338867,49.41745066666471],[8.681516647338867,49.41714356469011]]]}}}';

this one works, so either you should check your blah again or try removing the spaces in the body

1 Like