distance-matrix-2
Version:
Node.js wrapper for Goople Distance Matrix API.
66 lines (65 loc) • 2.6 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.requestJson = exports.stringifyQueryParams = exports.throwLocationsErrror = exports.formatLocations = exports.baseUrl = void 0;
const https_1 = __importDefault(require("https"));
const querystring_1 = require("querystring");
exports.baseUrl = "https://maps.googleapis.com/maps/api/distancematrix/json";
const formatLocations = (locations) => {
let res = "";
for (let i = 0; i < locations.length; i++) {
const location = locations[i];
const last = i !== locations.length - 1 ? "|" : "";
if (typeof location === "string") {
res += location + last;
}
else {
res += location.lat + "," + location.lng + last;
}
}
return res;
};
exports.formatLocations = formatLocations;
const throwLocationsErrror = (locations, name) => {
if (!locations || locations.length === 0) {
throw new Error(`Please provide a valid ${name} param.`);
}
for (let i = 0; i < locations.length; i++) {
const location = locations[i];
if (typeof location !== "string") {
if (typeof location !== "object" ||
typeof location.lat !== "number" ||
typeof location.lng !== "number") {
throw new Error(`Please provide a valid ${name} param (Position ${i}).`);
}
}
}
};
exports.throwLocationsErrror = throwLocationsErrror;
const stringifyQueryParams = (data, key) => {
(0, exports.throwLocationsErrror)(data.origins, "origins");
(0, exports.throwLocationsErrror)(data.destinations, "destinations");
return ("?" +
(0, querystring_1.stringify)(Object.assign(Object.assign({}, data), { origins: (0, exports.formatLocations)(data.origins), destinations: (0, exports.formatLocations)(data.destinations), key })));
};
exports.stringifyQueryParams = stringifyQueryParams;
const requestJson = (url) => {
return new Promise((resolve, reject) => {
https_1.default.get(url, (res) => {
let str = "";
/* istanbul ignore next */
res.on("error", (err) => {
reject(err);
});
res.on("data", (data) => {
str += data.toString();
});
res.on("end", () => {
resolve(JSON.parse(str.toString()));
});
});
});
};
exports.requestJson = requestJson;