diff --git a/README.md b/README.md index bcf9a9a..6f82095 100644 --- a/README.md +++ b/README.md @@ -32,3 +32,18 @@ L.Routing.control({ ``` Note that you will need to pass a valid GraphHopper API key to the constructor. + +To keep track of the GraphHopper credits consumption, the application may listen to the `response` event fired by the Router object. This event holds the values from [GraphHopper's response HTTP headers](https://graphhopper.com/api/1/docs/#http-headers): +* `status`: The HTTP status code (see [GraphHopper error codes](https://graphhopper.com/api/1/docs/#http-error-codes)) +* `limit`: The `X-RateLimit-Limit` header +* `remaining`: The `X-RateLimit-Remaining` header +* `reset`: The `X-RateLimit-Reset` header +* `credits`: The `X-RateLimit-Credits` header + +```javascript +var router = myRoutingControl.getRouter(); +router.on('response',function(e){ + console.log('This routing request consumed ' + e.credits + ' credit(s)'); + console.log('You have ' + e.remaining + ' left'); +}); +``` diff --git a/examples/index.html b/examples/index.html index b8bdc19..57f02dc 100644 --- a/examples/index.html +++ b/examples/index.html @@ -3,16 +3,16 @@ Leaflet OSRM Example - - + +
- - + + - \ No newline at end of file + diff --git a/examples/index.js b/examples/index.js index a9e2265..28425d0 100644 --- a/examples/index.js +++ b/examples/index.js @@ -4,7 +4,7 @@ L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '© OpenStreetMap contributors' }).addTo(map); -L.Routing.control({ +var routingControl = L.Routing.control({ waypoints: [ L.latLng(57.74, 11.94), L.latLng(57.6792, 11.949) @@ -13,3 +13,9 @@ L.Routing.control({ router: L.Routing.graphHopper('your-api-key'), routeWhileDragging: false }).addTo(map); + +var router = routingControl.getRouter(); +router.on('response',function(e){ + console.log('This request consumed ' + e.credits + ' credit(s)'); + console.log('You have ' + e.remaining + ' left'); +}); diff --git a/src/L.Routing.GraphHopper.js b/src/L.Routing.GraphHopper.js index 406a587..c7874db 100644 --- a/src/L.Routing.GraphHopper.js +++ b/src/L.Routing.GraphHopper.js @@ -7,7 +7,7 @@ L.Routing = L.Routing || {}; - L.Routing.GraphHopper = L.Class.extend({ + L.Routing.GraphHopper = L.Evented.extend({ options: { serviceUrl: 'https://graphhopper.com/api/1/route', timeout: 30 * 1000, @@ -55,6 +55,14 @@ clearTimeout(timer); if (!timedOut) { + var fired = err ? err : resp; + this.fire("response", { + status: fired.status, + limit: Number(fired.getResponseHeader("X-RateLimit-Limit")), + remaining: Number(fired.getResponseHeader("X-RateLimit-Remaining")), + reset: Number(fired.getResponseHeader("X-RateLimit-Reset")), + credits: Number(fired.getResponseHeader("X-RateLimit-Credits")) + }); if (!err) { data = JSON.parse(resp.responseText); this._routeDone(data, wps, callback, context);