Skip to content

Instantly share code, notes, and snippets.

@fayimora
Created April 4, 2016 23:03
Show Gist options
  • Save fayimora/75d77834800acc967193df15434595f0 to your computer and use it in GitHub Desktop.
Save fayimora/75d77834800acc967193df15434595f0 to your computer and use it in GitHub Desktop.
var distance = require('google-distance');
var _ = require('lodash');
module.exports = function (pubnub) {
pubnub.subscribe({
channel: "dispatch",
message: onNewDispatch
});
function onNewDispatch(message) {
const payload = JSON.parse(message);
var store = findClosestStore(payload.stores);
var rider = findRider(store);
var riderMessage = {
"delivery_id": payload.delivery_id,
"store": store
};
pubnub.publish({
channel: "riders."+rider.id
message: riderMessage,
callback: function (res) {
console.log("Succesfully dispatched delivery "+payload.delivery_id+" to "+rider.id);
}
});
}
function distanceBetween(origin, destination, callback) {
var distanceInMetres;
distance.get(
{origin: origin, destination: destination},
function (err, data) {
if(err) return console.log(err);
distanceInMetres = data.distanceValue;
}
);
return distanceInMetres;
}
function findStore(stores, destination) {
// here we want to find the closest store
stores = _.map(stores, function (store) {
store["distance"] = distanceBetween(store.address, destination);
return store;
});
stores = _.sortBy(stores, 'distance');
}
function findRider(store) {
var riderIds;
pubnub.here_now({
channel: 'riders.*',
callback: function (m) {
riderIds = m.uuids;
}
});
}
};
@bigmeech
Copy link

bigmeech commented Apr 5, 2016

var async = require('async');
var stores = [] //fill with something
function distanceBetween(destination, store, callback) {
    distance.get({ origin: store.address, destination: destination }, function (err, data) {
        if(err) return callback(err);
        store.distanceValue = data.distanceValue;
        return callback(null, store);
      }
    );
  }

function getDistances = function(err, results){
        //results should be a collection with your real distance values in store.distanceValue
}
async.map(stores, distanceBetween.bind(null, destination), getDistances)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment