Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
OSRM Distance Matrix
var request = require('simple-get'),
extend = require('extend');
function DistanceMatrix(features, options) {
this.options = extend({}, { serviceUrl: 'http://router.project-osrm.org/table'}, options);
this._features = features.features.reduce(function(fs, f, i) {
if (f.geometry.type !== 'Point') {
throw 'Feature geometries must be Points.';
}
var key = f.geometry.coordinates.toString();
fs[key] = {
index: i,
feature: f
};
return fs;
}, {});
}
DistanceMatrix.prototype.getDistance = function(f1, f2, cb) {
var getDistance = function() {
var k1 = f1.geometry.coordinates.toString(),
k2 = f2.geometry.coordinates.toString(),
i = this._features[k1].index,
j = this._features[k2].index;
console.log(k1, k2, i, j);
console.log(this._matrix);
cb(undefined, this._matrix[i][j]);
}.bind(this);
if (!this._matrix) {
this._fetchMatrix(function(err) {
if (!err) {
getDistance();
} else {
cb(err);
}
});
} else {
getDistance();
}
};
DistanceMatrix.prototype._fetchMatrix = function(cb) {
var locs = Object.keys(this._features).map(function(k) {
var f = this._features[k].feature,
cs = f.geometry.coordinates;
return 'loc=' + cs[1] + ',' + cs[0];
}.bind(this)),
url = this.options.serviceUrl + '?' + locs.join('&');
request.concat(url, function(err, data, res) {
if (err) {
cb(err);
} else {
if (res.statusCode !== 200) {
cb({
code: 'HTTP_ERROR',
statusCode: res.statusCode,
response: data.toString()
});
} else {
var dt = JSON.parse(data.toString()).distance_table;
if (!dt) {
cb({
code: 'MISSING_DISTANCE_TABLE',
message: 'Distance table is missing from server response.',
response: data.toString()
});
} else {
this._matrix = data.distance_table;
cb();
}
}
}
}.bind(this));
};
module.exports = DistanceMatrix;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment