-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
75 lines (55 loc) · 3.21 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
const express = require('express')
const turf = require('@turf/turf')
const testDataSample1 = require('./data/plowpath')
const transformer = require('./src/transformer')
const app = express()
const port = 3000
const requestHandler = async (req, res) => {
transformer.sortByDate(testDataSample1)
const groupedIds = transformer.groupByAssetId(testDataSample1)
const optimizedPaths = Object.keys(groupedIds).map((key) => {
const currentGroup = groupedIds[key]
transformer.addTurfPath(currentGroup)
for (let currentCursor = 0; currentCursor < currentGroup.length; currentCursor++) {
const latestSegment = currentGroup[currentCursor]
const latestTurfPath = latestSegment.turfPath
for(let subCursor = currentCursor+1; subCursor < currentGroup.length; subCursor++){
const oldSegment = currentGroup[subCursor]
const oldTurfPath = oldSegment.turfPath
const intersection = turf.lineIntersect(latestTurfPath, oldTurfPath)
if(intersection.features.length > 2){
const newPath = []
const firstIntersection = intersection.features[0].geometry
const lastIntersection = intersection.features[intersection.features.length - 1].geometry
const distanceLatestToFirst = transformer.calculateDistance(latestTurfPath.geometry.coordinates[0], firstIntersection.coordinates)
const distanceCurrentToFirst = transformer.calculateDistance(oldTurfPath.geometry.coordinates[0], firstIntersection.coordinates)
const firstDistanceDifference = distanceLatestToFirst - distanceCurrentToFirst
const closestEndPath = transformer.slicePathFromIntersectionToEnd(lastIntersection.coordinates, oldTurfPath.geometry.coordinates)
const newEndPath = transformer.buildNewPath(oldSegment.timestamp, closestEndPath)
newPath.push(newEndPath)
if (Math.abs(firstDistanceDifference) > 0.01) { //IF: latest Path are closed to old Path
const closestStartPath = transformer.slicePathFromStartToIntersection(firstIntersection.coordinates, oldTurfPath.geometry.coordinates)
const newStartPath = transformer.buildNewPath(oldSegment.timestamp, closestStartPath)
newPath.unshift(newStartPath)
}
currentGroup.splice(subCursor, 1, ...newPath)
if(newPath.length === 2) subCursor++
}
}
}
for (let i = 0; i < currentGroup.length; i++) {
if (!currentGroup[i].readings) {
currentGroup[i].readings = transformer.convertToReading(currentGroup[i].turfPath.geometry.coordinates)
}
delete currentGroup[i].turfPath
}
return currentGroup
})
const finalOptimizedPaths = optimizedPaths.reduce((prev, curr) => {
return prev.concat(curr)
})
res.status(200)
res.json(finalOptimizedPaths)
}
app.get('/', requestHandler)
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))