-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
86 lines (66 loc) · 2.11 KB
/
server.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
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/env node --max-old-space-size=4096
const {features} = require('./dist/iris.json')
const express = require('express')
const {chain, min} = require('lodash')
const Flatbush = require('flatbush')
const {bbox: getBbox, booleanPointInPolygon, point, lineString, pointToLineDistance} = require('@turf/turf')
const morgan = require('morgan')
const cors = require('cors')
const app = express()
const geoIndex = new Flatbush(features.length)
features.forEach(f => geoIndex.add(...getBbox(f)))
geoIndex.finish()
if (process.env.NODE_ENV === 'production') {
app.enable('trust proxy')
}
app.use(cors({origin: true}))
if (process.env.NODE_ENV !== 'production') {
app.use(morgan('dev'))
}
app.get('/iris', (req, res) => {
if (!req.query.lat || !req.query.lon || !req.query.codeCommune) {
return res.sendStatus(400)
}
const lat = Number.parseFloat(req.query.lat)
const lon = Number.parseFloat(req.query.lon)
if (lat > 90 || lat < -90 || lon > 180 || lon < -180) {
return res.sendStatus(400)
}
const candidates = geoIndex.neighbors(lon, lat, 10, 10, undefined)
.filter(i => features[i].properties.codeCommune === req.query.codeCommune)
.map(i => features[i])
if (candidates.length === 0) {
return res.sendStatus(404)
}
const exactResult = candidates.find(c => {
return booleanPointInPolygon(
point([lon, lat]),
c
)
})
if (exactResult) {
return res.send(exactResult.properties)
}
const fuzzyResult = chain(candidates)
.minBy(c => {
const rings = []
if (c.geometry.type === 'Polygon') {
rings.push(...c.geometry.coordinates)
}
if (c.geometry.type === 'MultiPolygon') {
c.geometry.coordinates.forEach(polygonRings => rings.push(...polygonRings))
}
return min(rings.map(ring => {
return pointToLineDistance(point([lon, lat]), lineString(ring), {units: 'kilometers'})
}))
})
.value()
if (fuzzyResult) {
return res.send(fuzzyResult.properties)
}
res.sendStatus(404)
})
const port = process.env.PORT || 5000
app.listen(port, () => {
console.log(`Start listening on port ${port}`)
})