mirror of https://github.com/pelias/api.git
Diana Shkolnikov
9 years ago
6 changed files with 79 additions and 1 deletions
@ -0,0 +1,32 @@
|
||||
var geolib = require('geolib'); |
||||
|
||||
|
||||
function setup() { |
||||
|
||||
return computeDistances; |
||||
} |
||||
|
||||
function computeDistances(req, res, next) { |
||||
|
||||
// do nothing if no result data set
|
||||
if (!req.results || !req.results.data) { |
||||
return next(); |
||||
} |
||||
|
||||
if ( !(req.clean.hasOwnProperty('lat') && req.clean.hasOwnProperty('lon')) ) { |
||||
return next(); |
||||
} |
||||
|
||||
req.results.data.forEach(function (place) { |
||||
// the result of getDistance is in meters, so convert to kilometers
|
||||
place.distance = geolib.getDistance( |
||||
{ latitude: req.clean.lat, longitude: req.clean.lon }, |
||||
{ latitude: place.center_point.lat, longitude: place.center_point.lon } |
||||
) / 1000; |
||||
}); |
||||
|
||||
next(); |
||||
} |
||||
|
||||
|
||||
module.exports = setup; |
@ -0,0 +1,41 @@
|
||||
var distance = require('../../../middleware/distance')(); |
||||
|
||||
module.exports.tests = {}; |
||||
|
||||
module.exports.tests.computeDistance = function(test, common) { |
||||
test('valid lat/lon and results', function(t) { |
||||
var req = { |
||||
clean: { |
||||
lat: 45, |
||||
lon: -77 |
||||
}, |
||||
results: { |
||||
data: [ |
||||
{ |
||||
center_point: { |
||||
lat: 40, |
||||
lon: -71 |
||||
} |
||||
} |
||||
] |
||||
} |
||||
}; |
||||
|
||||
var expected = 742.348; |
||||
distance(req, null, function () { |
||||
t.equal(req.results.data[0].distance, expected, 'correct distance computed'); |
||||
t.end(); |
||||
}); |
||||
}); |
||||
}; |
||||
|
||||
module.exports.all = function (tape, common) { |
||||
|
||||
function test(name, testFunction) { |
||||
return tape('[middleware] distance: ' + name, testFunction); |
||||
} |
||||
|
||||
for( var testCase in module.exports.tests ){ |
||||
module.exports.tests[testCase](test, common); |
||||
} |
||||
}; |
Loading…
Reference in new issue