78 lines
2.8 KiB
JavaScript
78 lines
2.8 KiB
JavaScript
|
const UserError = require('vn-loopback/util/user-error');
|
||
|
const axios = require('axios');
|
||
|
|
||
|
module.exports = Self => {
|
||
|
Self.remoteMethod('optimize', {
|
||
|
description: 'Return optimized coords',
|
||
|
accessType: 'READ',
|
||
|
accepts: [{
|
||
|
arg: 'addressIds',
|
||
|
type: 'array',
|
||
|
required: true
|
||
|
}],
|
||
|
returns: {
|
||
|
type: 'string',
|
||
|
root: true
|
||
|
},
|
||
|
http: {
|
||
|
path: `/optimize`,
|
||
|
verb: 'GET'
|
||
|
}
|
||
|
});
|
||
|
|
||
|
Self.optimize = async addressIds => {
|
||
|
const models = Self.app.models;
|
||
|
try {
|
||
|
const locationiqConfig = await models.LocationiqConfig.findOne();
|
||
|
if (!locationiqConfig) throw new UserError(`LocationIQ service is not configured`);
|
||
|
|
||
|
let coords = [];
|
||
|
for (const addressId of addressIds) {
|
||
|
const address = await models.Address.findById(addressId);
|
||
|
coords.push({
|
||
|
addressId,
|
||
|
latitude: address.latitude.toFixed(6),
|
||
|
longitude: address.longitude.toFixed(6)
|
||
|
});
|
||
|
}
|
||
|
const concatCoords = coords
|
||
|
.map(coord => `${coord.longitude},${coord.latitude}`)
|
||
|
.join(';');
|
||
|
const response = await axios.post(`${locationiqConfig.url}${concatCoords}?key=${locationiqConfig.key}`);
|
||
|
const tolerance = locationiqConfig.tolerance;
|
||
|
|
||
|
for (waypoint of response.data.waypoints) {
|
||
|
const longitude = waypoint.location[0];
|
||
|
const latitude = waypoint.location[1];
|
||
|
|
||
|
const matchedAddress = coords.find(coord =>
|
||
|
Math.abs(coord.latitude - latitude) <= tolerance &&
|
||
|
Math.abs(coord.longitude - longitude) <= tolerance
|
||
|
);
|
||
|
if (matchedAddress) matchedAddress.position = waypoint.waypoint_index;
|
||
|
}
|
||
|
coords.sort((a, b) => {
|
||
|
const posA = a.position !== undefined ? a.position : Infinity;
|
||
|
const posB = b.position !== undefined ? b.position : Infinity;
|
||
|
return posA - posB;
|
||
|
});
|
||
|
// Temporal para abrir en maps
|
||
|
const coordsString = coords
|
||
|
.map(item => `${item.latitude},${item.longitude}`)
|
||
|
.join('/');
|
||
|
console.log(`https://www.google.es/maps/dir/${coordsString}`);
|
||
|
// ---------
|
||
|
return coords;
|
||
|
} catch (err) {
|
||
|
switch (err.response?.data?.code) {
|
||
|
case 'NoTrips':
|
||
|
throw new UserError('No trips found because input coordinates are not connected');
|
||
|
case 'NotImplemented':
|
||
|
throw new UserError('This request is not supported');
|
||
|
default:
|
||
|
throw err;
|
||
|
}
|
||
|
}
|
||
|
};
|
||
|
};
|