'use strict';
var _Promise = require('babel-runtime/core-js/promise')['default'];
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.findMatches = findMatches;
var _rbush = require('rbush');
var _rbush2 = _interopRequireDefault(_rbush);
var _turfDestination = require('turf-destination');
var _turfDestination2 = _interopRequireDefault(_turfDestination);
var _turfDistance = require('turf-distance');
var _turfDistance2 = _interopRequireDefault(_turfDistance);
var _turfPoint = require('turf-point');
var _turfPoint2 = _interopRequireDefault(_turfPoint);
/**
* Make a SOAP request to [Commuter Connections](http://www.commuterconnections.org/) to get the number of carpools available for a given starting, ending location, and search radius.
*
* @param {Object} opts Options object
* @returns {Promise} promise
* @example
* import {findMatches} from 'commuter-connections'
* findMatches({
* commuters: [{
* _id: 1,
* coordinates: [-77.4875, 39.0436]
* }], {
* radius: .5,
* units: 'miles'
* }}).then((matches) => {
* console.log(matches) // map of commuter id's to matching commuter id's
* }, handleError)
*/
function findMatches(commuters) {
var opts = arguments[1] === undefined ? {} : arguments[1];
return new _Promise(function (resolve, reject) {
Iif (!commuters) return reject('No commuters.');
var tree = (0, _rbush2['default'])();
tree.load(commuters.map(function (c) {
return [c.coordinates[0], c.coordinates[1], c.coordinates[0], c.coordinates[1], c];
}));
var responses = [];
var RADIUS = opts.radius || 0.25;
var DIST = RADIUS * Math.sqrt(2);
var UNITS = opts.units || 'miles';
commuters.forEach(function (commuter) {
var fromPoint = (0, _turfPoint2['default'])(commuter.coordinates);
// construct bbox
var bottomLeft = (0, _turfDestination2['default'])(fromPoint, DIST, -135, UNITS);
var topRight = (0, _turfDestination2['default'])(fromPoint, DIST, 45, UNITS);
// do the initial bbox search
var results = tree.search(bottomLeft.geometry.coordinates.concat(topRight.geometry.coordinates));
// filter the matches
var matches = results.reduce(function (matches, result) {
var match = result[4]._id;
var matchPoint = (0, _turfPoint2['default'])([result[0], result[1]]);
// ignore self match
if (match === commuter._id) return matches;
// ignore matches where distance exceeds search radius
var distance = (0, _turfDistance2['default'])(fromPoint, matchPoint);
if (distance > RADIUS) return matches;
matches.push({
_id: match,
distance: distance
});
return matches;
}, []);
responses.push({
_id: commuter._id,
matches: matches
});
});
resolve(responses);
});
}
|