Coder Social home page Coder Social logo

giscience / openrouteservice-js Goto Github PK

View Code? Open in Web Editor NEW
185.0 17.0 35.0 1.99 MB

:pushpin: The JavaScript API to consume openrouteservice(s) painlessly!

Home Page: https://openrouteservice.org

License: Apache License 2.0

JavaScript 97.48% HTML 1.05% Vue 1.29% Shell 0.18%
npm-package npm nodejs openrouteservice sdk api routing-engine

openrouteservice-js's Introduction

The JavaScript API to consume openrouteservice(s) painlessly!

Build and test codecov

This library lets you consume the openrouteservice API in JavaScript applications. It allows you to painlessly consume the following services:

  • Directions (routing)
  • Geocoding | Reverse Geocoding | Structured Geocoding (powered by Pelias)
  • Isochrones (accessibility)
  • Time-distance matrix
  • POIs (points of interest)
  • Elevation (linestring or point)
  • Optimization

See the examples in the examples folder

Note: In order to use this client, you have to register for a token at openrouteservice. To understand the features of openrouteservice, please don't forget to read the docs. For visualization purposes on the map please use openrouteservice maps.

Documentation

This library uses the ORS API for request validation. To understand the input of each API specifically, please check API Playground that provides an interactive documentation.

Installation and Usage

Requirements

  • git
  • nodeJS
  • if not included in nodeJS: npm

Install the library with npm:

npm install openrouteservice-js --save

Use es module import

import Openrouteservice from 'openrouteservice-js'
let orsDirections = new Openrouteservice.Directions({ api_key: "XYZ"});
// ...

Use requirejs

const Openrouteservice = require("openrouteservice-js");
let orsDirections = new Openrouteservice.Directions({ api_key: "XYZ"});
// ...

Use the distribution file directly in html

<script type="module" src="../openrouteservice-js/dist/ors-js-client.js"></script>
<script>
  let orsDirections = new Openrouteservice.Directions({ api_key: "XYZ"});
  // ...
</script>

Pair with local openrouteservice instance

// Note: The API key is currently still passed as a parameter but not needed by the local instance
import Openrouteservice from 'openrouteservice-js'
let orsDirections = new Openrouteservice.Directions(
  { host: "http://localhost:8082/ors" }
);
// ...

Integrate the APIs in your application

Isochrones Example

// Add your api_key here
const Isochrones = new Openrouteservice.Isochrones({ api_key: "XYZ"})
try {
  let response = await Isochrones.calculate({
    locations: [[8.690958, 49.404662], [8.687868, 49.390139]],
    profile: 'driving-car',
    range: [600],
    units: 'km',
    range_type: 'distance',
    attributes: ['area'],
    smoothing: 0.9,
    avoidables: ['highways'],
    avoid_polygons: {
      type: 'Polygon',
      coordinates: [
        [
          [8.683533668518066, 49.41987949639816],
          [8.680272102355957, 49.41812070066643],
          [8.683919906616211, 49.4132348262363],
          [8.689756393432617, 49.41806486484901],
          [8.683533668518066, 49.41987949639816]
        ]
      ]
    },
    area_units: 'km'
  })
  // Add your own result handling here
  console.log("response: ", response)
    
} catch (err) {
  console.log("An error occurred: " + err.status)
  console.error(await err.response.json())
}

Directions HGV example (browser)

Note: Nested parameters from the options object are easier accessible like restrictions, avoidables and avoid_polygons (cf. API docs)

<script>
  window.onload = async function() {
    // Add your api_key here
    let orsDirections = new Openrouteservice.Directions({ api_key: "XYZ"});

    try {
      let response = await orsDirections.calculate({
        coordinates: [[8.690958, 49.404662], [8.687868, 49.390139]],
        profile: 'driving-hgv',
        restrictions: {
          height: 10,
          weight: 5
        },
        extra_info: ['waytype', 'steepness'],
        avoidables: ['highways', 'tollways', 'ferries', 'fords'],
        avoid_polygons: {
          type: 'Polygon',
          coordinates: [
            [
              [8.683533668518066, 49.41987949639816],
              [8.680272102355957, 49.41812070066643],
              [8.683919906616211, 49.4132348262363],
              [8.689756393432617, 49.41806486484901],
              [8.683533668518066, 49.41987949639816]
            ]
          ]
        },
        format: 'json'
      })
      // Add your own result handling here
      console.log("response: ", response)

    } catch (err) {
      console.log("An error occurred: " + err.status)
      console.error(await err.response.json())
    }
  };
</script>

Geocode examples

// Add your api_key here
const Geocode = new Openrouteservice.Geocode({ api_key: "XYZ"})

try {
  let response = await Geocode.geocode({
    text: "Heidelberg",
    boundary_circle: { lat_lng: [49.412388, 8.681247], radius: 50 },
    boundary_bbox: [[49.260929, 8.40063], [49.504102, 8.941707]],
    boundary_country: ["DE"]
  })
  // Add your own result handling here
  console.log("response: ", response)

} catch (err) {
  console.log("An error occurred: " + err.status)
  console.error(await err.response.json())
}

try {
  let response_reverse = await Geocode.reverseGeocode({
  point: { lat_lng: [49.412388, 8.681247], radius: 50 },
  boundary_country: ["DE"]
})
  // Add your own result handling here
  console.log("response: ", response_reverse)

} catch (err) {
  console.log("An error occurred: " + err.status)
  console.error(await err.response.json())
}


try {
  let response_structured = await Geocode.structuredGeocode({
  locality: "Heidelberg"
})
  // Add your own result handling here
  console.log("response: ", response_structured)

} catch (err) {
  console.log("An error occurred: " + err.status)
  console.error(await err.response.json())
}

Matrix example

// Add your api_key here
const Matrix = new Openrouteservice.Matrix({ api_key: "XYZ"})

try {
  let response = Matrix.calculate({
  locations: [[8.690958, 49.404662], [8.687868, 49.390139], [8.687868, 49.390133]],
  profile: "driving-car",
  sources: ['all'],
  destinations: ['all']
})
  // Add your own result handling here
  console.log("response: ", response)

} catch (err) {
  console.log("An error occurred: " + err.status)
  console.error(await err.response.json())
}

Elevation example

// Add your api_key here
const Elevation = new Openrouteservice.Elevation({api_key: "XYZ"})

try {
  let response = Elevation.lineElevation({
  format_in: 'geojson',
  format_out: 'geojson',
  geometry: {
    coordinates: [[13.349762, 38.11295], [12.638397, 37.645772]],
    type: 'LineString'
  }
})
  // Add your own result handling here
  console.log("response: ", response)

} catch (err) {
  console.log("An error occurred: " + err.status)
  console.error(await err.response.json())
}

Optimization example

Or consume Optimization API to solve vehicle routing problems

// Add your api_key here
let Optimization = new openrouteservice.Optimization({api_key: "XYZ"});

try {
  let response = Optimization.optimize({
  jobs: [
    {
      id: 1,
      service: 300,
      amount: [1],
      location: [2.03655, 48.61128],
      skills: [1]
    },
    {
      id: 2,
      service: 300,
      amount: [1],
      location: [2.03655, 48.61128],
      skills: [2]
    },
  ],
  vehicles: [
    {
      id: 1,
      profile: 'driving-car',
      start: [2.35044, 48.71764],
      end: [2.35044, 48.71764],
      capacity: [3],
      skills: [1, 2],
    }
  ],
})
  // Add your own result handling here
  console.log("response: ", response)

} catch (err) {
  console.log("An error occurred: " + err.status)
  console.error(await err.response.json())
}

Development Setup

Clone the openrouteservice-js repository from GitHub into a development environment of your choice.

git clone https://github.com/GIScience/openrouteservice-js.git
cd openrouteservice-js

# Install the dependencies
npm install

# Make your openrouteservice API key available for tests, examples and dev_app
sh setup.sh <your-api-key>

Start the dev_app for debugging when working with source files:

# runs the app at http://localhost:5173
vite

Now you can either use the devtools of your browser to set breakpoints (e.g. in OrsGeocode) or create a JavaScript Debug configuration to debug with WebStorm: debug_config

Run the config in debug mode to open the Chrome browser and reload the page after changes for them to take effect immediately.

Running Tests

To run specific unit test files in src/__tests__ on demand during development, run

npm run test:e2e

Choose one of your installed browsers in the cypress UI you want to test in and select the test file you want to run.

Component tests for the web app can be run by switching to component testing.

To run tests without ui use the npm scripts ending with :ci e.g. for unit, component and e2e tests:

npm run test:ci

Commits and versioning

  • This app uses the commitizen plugin to generate standardized commit types/messages. After applying any change in a feature branch, use git add . and then npm run commit (instead of git commit ...)
  • The plugin standard-version is used to generate changelog entries, version tag and to bump the app version in package.json.

Deployment flow:

  • Apply the changes in a feature branch and test it locally
  • Once the feature is ready, merge it to develop, deploy it to the testing environment
  • Checkout in main, merge from develop and use npm run release to generate a release. This will generate a new release commit as well as a git tag and an entry in CHANGELOG.md.

For more details about commitizen and standard-version see this article

openrouteservice-js's People

Contributors

amoncaldas avatar damian66 avatar emmahegarty avatar stefanocudini avatar thegreatrefrigerator avatar timmccauley avatar uniquename avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

openrouteservice-js's Issues

Fixup README.md

  • The Documentation part can be truncuated to the first two sentences (feature list is same as above).

  • Add development setup instructions.

Support to Optimization Api

hi

I was wondering why the optimization API was not included, in python bindings it is present.

would you accept a PR having this?
or is it not present for other technical or commercial reasons?

best regards
Stefano

vulnerability issue: http-server dependency

When installing this module, npm reports a moderate-severity vulnerability caused by the required version of http-server, which is 0.12.3, that requires a vulnerable version of ecstatcic (<4.1.3).
The earliest non-vulnerable version of http-server seems to be 0.13.0, since it does not require the now unsupported ecstatic package.
Also, it seems like openrouteservice-js does not utilize http-server on top level. If that's the case, the dependency could be removed, fixing the vulnerability problem and removing a useless package too.

Bug: Impossible to set avoidables for directions

After updating the package openrouteservice-js from version 0.1.16 to 0.1.20, following error occurs

TypeError: Cannot set property 'avoid_features' of undefined
    at OrsDirections.getBody (/home/FILEPATH/node_modules/openrouteservice-js/npm_distribution/OrsDirections.js:100:37)
    at /home/FILEPATH/node_modules/openrouteservice-js/npm_distribution/OrsDirections.js:130:29
    at Promise._execute (/home/FILEPATH/node_modules/bluebird/js/release/debuggability.js:384:9)
    at Promise._resolveFromExecutor (/home/FILEPATH/node_modules/bluebird/js/release/promise.js:518:18)
    at new Promise (/home/FILEPATH/node_modules/bluebird/js/release/promise.js:103:10)
    at OrsDirections.calculate (/home/FILEPATH/node_modules/openrouteservice-js/npm_distribution/OrsDirections.js:121:14)
    at /home/FILEPATH/models/openrouteservice.js:32:32
    at /home/FILEPATH/plugins/outbound/wallboard/service.js:270:45
    at /home/FILEPATH/models/openrouteservice.js:31:7
    at Statement.<anonymous> (/home/FILEPATH/models/configuration.js:50:28)
TypeError: Cannot set property 'avoid_features' of undefined
    at OrsDirections.getBody (/home/FILEPATH/node_modules/openrouteservice-js/npm_distribution/OrsDirections.js:100:37)
    at /home/FILEPATH/node_modules/openrouteservice-js/npm_distribution/OrsDirections.js:130:29
    at Promise._execute (/home/FILEPATH/node_modules/bluebird/js/release/debuggability.js:384:9)
    at Promise._resolveFromExecutor (/home/FILEPATH/node_modules/bluebird/js/release/promise.js:518:18)
    at new Promise (/home/FILEPATH/node_modules/bluebird/js/release/promise.js:103:10)
    at OrsDirections.calculate (/home/FILEPATH/node_modules/openrouteservice-js/npm_distribution/OrsDirections.js:121:14)
    at /home/FILEPATH/models/openrouteservice.js:32:32
    at /home/FILEPATH/plugins/outbound/wallboard/service.js:270:45
    at /home/FILEPATH/models/openrouteservice.js:31:7
    at Statement.<anonymous> (/home/FILEPATH/models/configuration.js:50:28)

Here is my code snippet to reproduce the error:

 this.directions = new openrouteservice.Directions({
        api_key: apiKey
      });
      callback(() => {
        return this.directions.calculate({
          coordinates: [start, destination],
          profile: 'driving-car',
          extra_info: ['waytype', 'steepness'],
          avoidables: ['tollways', 'ferries', 'fords'],
          format: 'geojson'
        })
      })

After removing the line avoidables: ['tollways', 'ferries', 'fords'], the package works as intented.

URL for Matrix Service is wrong

When we use Matrix service
Matrix.calculate({ locations: [[8.690958, 49.404662], [8.687868, 49.390139], [8.687868, 49.390133]], profile: "driving-car", sources: ['all'], destinations: ['all'] })
Browser send request to https://api.openrouteservice.org/matrix/v2/matrix/driving-car/json
Word 'matrix' uses twice in URL

Directions geojson format problem

I use this code:

var Ors = Npm.require('openrouteservice-js');

var directions = new Ors.Directions({
	api_key: '<MY_SECRET_KEY>'
});
directions.calculate({
	instructions: false,
	coordinates: [[10.88476896,45.92084111],[10.89092731,45.92013953]],
	format: 'geojson'
})
.then(function(json) {
	console.log('then', json)
})
.catch(function(err) {
	console.warn("error",err);
});

that produce this request:

POST /v2/directions/foot-hiking/geojson HTTP/1.1
Host: api.openrouteservice.org
Accept-Encoding: gzip, deflate
User-Agent: node-superagent/4.1.0
Content-Type: application/json
Authorization: <MY_SECRET_KEY>
Accept: application/json
Content-Length: 186
Connection: close

{"instructions":false,"coordinates":[[10.88476896,45.92084111],[10.89092731,45.92013953]],"preference":"fastest","units":"m","language":"en","geometry":true,"instructions_format":"text"}

but is show an exception:

{"error":{"code":2007,"message":"This response format is not supported"}

I think the problem is Accept: application/json instead of Accept: application/geo+json
A simple patch is in this PR: #14

issue:

Configuration

  • ORS Client: "openrouteservice-js": "^0.3.2"
  • Node.js: v18.8.0.
  • Target geography: United States, Oregon
  • Parameters passed to Openrouteservice.Isochrones.calculate below (5 point geometries passed in locations
    image

Issue:
When running Isochrone operations using the openrouteservice-js client, seeing intermittent issues with 'Operation was abortederrors. Error below.err.code` is 20.

Stack Trace.
`'AbortError: The operation was aborted.
at new DOMException (node:internal/per_context/domexception:53:5)
at abortFetch (node:internal/deps/undici/undici:6374:21)
at requestObject.signal.addEventListener.once (node:internal/deps/undici/undici:6308:9)
at [nodejs.internal.kHybridDispatch] (node:internal/event_target:731:20)
at AbortSignal.dispatchEvent (node:internal/event_target:673:26)
at abortSignal (node:internal/abort_controller:292:10)
at AbortController.abort (node:internal/abort_controller:322:5)
at AbortSignal.abort (node:internal/deps/undici/undici:5636:36)
at [nodejs.internal.kHybridDispatch] (node:internal/event_target:731:20)
at AbortSignal.dispatchEvent (node:internal/event_target:673:26)'

feature request: Add optimization endpoint

Hello,
I'm still discovering this module and I found out that there isn't support for the Optimization API.
I've seen that the last time someone talked about it was in #31, has anything changed since this?
Will y'all be able to implement it? Or is there any documentation about how I could do it myself? There isn't proper code documentation but maybe you have a spec or something, I don't know.
Thanks again!

bug: Cannot get geocoding for some adresses

Hey,
I've recently discovered this module that is just amazing, first thing first, thanks to y'all guys, this is genuinely awesome and this is a great example of why the open source community is awesome, writing all the requests manually would have been a HUGE pain.

I have a problem with the Geocoding API tho.
I'm trying to get the results for a string. I can't provide it to you guys because it contains private information, but I'm trying to find an example I could use that has the same behavior as mine.

Sometimes, especially with accented strings apparently, the geocoder doesn't get the address right and the parsing isn't done properly, which results in no point data at all.
After further debugging, I eventually noticed the parser was faulty, because the API returned an URI-encoded string in the result["geocoding"]["query"]["text"] element.
Though, apparently only accented characters get URI-encoded, since spaces and special characters aren't.
I tested this on OpenROuteService's website and it does work, here the whole string is encoded, not just parts of it.
In my script, the used parser is pelias, whereas on the website it is libpostal. pelias doesn't recognize anything at all while libpostal is able to determine how is the address string composed.

I hope my explanation is clear and that you will be able to help me solve this problem.
In the meantime I'm trying to get it working by myself, if I find anything I'll update you from this issue.
Thanks again and good night! :)

Define service endpoint as a parameter, instead of hard coded

As 'directions', 'isochrones' and 'matrix' are hard coded in the code, it is not possible to use an alternative service endpoint, like, for eg. 'pdirections', 'pisochrones' and 'pmatrix'.

A small change would improve the flexibility of the package. The suggestion is:

[OrsDirections.js]
L 99:
value: function calculate(reqArgs)
[becames]:
value: function calculate(reqArgs, service = 'directions')
L 110:
var requestSettings = orsUtil.prepareRequest(that.args, 'directions');
[becames]:
var requestSettings = orsUtil.prepareRequest(that.args, service);

Apply the same approach to for ORSIsochones.js and OrsMatrix.js

Allow to use self-hosted ORS

Maybe I'm missing something, but I think this API can't be used with self-hosted instances of OpenRouteService. Would it be possible to add support for this?

not found

Hi, thanks for this great tool, I have the following query, on the interactive map I have this test route
https://www.openstreetmap.org/directions?engine=fossgis_osrm_car&route=40.4442%2C-3.8037%3B40.4412%2C-3.7914#map=16/40.4414/-3.7980
and the system gives me the relevant data and routes, all ok, now when I want to pass the range of [40.4442, -3.8037], [40.4412, -3.7914] to the api
Directions.calculate ({ coordinates: [[40.4442, -3.8037], [40.4412, -3.7914]], profile: 'driving-car', extra_info: ['waytype', 'steepness'], format: 'json' }) .then (function (json) { console.log (JSON.stringify (json)) }) .catch (function (err) { const str = 'An error occured:' + err console.log (str) })

Ireturn the error An error occured: Error: Not Found

please some help to fix it, thanks

Interval has incorrect value or format (JS API)

When trying to fetch isochrones using the Javascript API:

 const geojson = await Isochrones.calculate({
   locations: [[lon, lat]],
   profile: profile,
   range: [900],
   range_type: 'time',
   area_units: 'm',
   units: 'm',
   interval: [300]
 })

I get the following error message:

"error":{"code":3002,"message":"Parameter \'interval\' has incorrect value or format
According to the OrsIsochroneSchema.js, it can be a list of multiple ranges, e.g. [600, 1200, 1400] or a single value list.

Neither [300] nor [300, 600, 900] are working.

Extract base class for services

api key code is duplicated for each service.
A base parent class providing the api key functionality would be a better approach

nodejs env not work

I have this file test.js

var Openrouteservicejs = require('openrouteservice-js');
console.log(Openrouteservicejs);

running this in nodejs v10.6.0, cause:

$ node test.js 
Using browser-only version of superagent in non-browser environment
{}

Alternative Routes

Does this library have something for alternative routes? because in the request body i add the alternative route option and returns bad request

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.