-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
64 lines (58 loc) · 1.88 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
let {Client} = require('pg')
let express = require ("express")
let app = express();
app.use(express.json())
let client = new Client({
user: "postgres",
password: "password",
host: "localhost",
port: 5432,
database: "route1"
})
app.get("/", (req, res) => res.sendFile(`${__dirname}/index.html`))
app.get("/styles.css", (req, res) => res.sendFile(`${__dirname}/styles.css`))
app.get("/osm.mapml", (req, res) => res.sendFile(`${__dirname}/osm.mapml`))
app.get("/labelled_imagery.mapml", (req, res) => res.sendFile(`${__dirname}/labelled_imagery.mapml`))
app.use('/mapml', (req, res) => {
res.sendFile(__dirname + req.originalUrl)
})
//Used for Testing
app.get("/test", (req, res) => {
res.send("<h1>It's working</h1>")
})
app.get("/getpath", async (req, res) => {
let result = {};
try{
result = await getResults(req.query.start, req.query.end);
}
catch(e) {
result.success = false;
}
finally {
res.setHeader("content-type", "application/json");
res.send(result);
}
})
app.listen(3001, () => console.log("Web Server is listening... on port 3001"));
start();
async function start() {
await connect();
}
async function connect() {
try {
await client.connect();
}
catch(e) {
console.error(`Failed to connect ${e}`);
}
}
async function getResults(start, end) {
let text = `SELECT jsonb_build_object('type','Feature','title','Path','geometry',t.geom,'properties', 'Path') AS json FROM (SELECT ST_Collect(the_geom) AS geom FROM pgr_dijkstra('SELECT gid as id, source, target, cost FROM ways', ${start}, ${end}, directed := FALSE) AS route LEFT JOIN ways ON route.edge = ways.gid) t;`;
try {
let res = await client.query(text);
return JSON.stringify(res.rows[0]);
}
catch(e) {
return [];
}
}