forked from HSLdevcom/tilelive-otp-citybikes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
107 lines (91 loc) · 2.37 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
"use strict"
const geojsonVt = require('geojson-vt');
const vtPbf = require('vt-pbf');
const request = require('requestretry');
const zlib = require('zlib');
const url = process.env.GRAPHQL_URL || "https://api.digitransit.fi/routing/v1/routers/hsl/index/graphql";
const query = `
query bikerentals {
bikeRentalStations {
stationId
name
networks
lon
lat
}
}`
class OtpCityBikeSource {
constructor(uri, callback){
this.uri = url;
callback(null, this);
};
fetchBikeRentals(callback) {
request({
url: this.uri,
body: query,
maxAttempts: 120,
retryDelay: 30000,
method: "POST",
headers: {
'Content-Type': 'application/graphql'
}
}, function (err, res, body){
if (err){
console.log(err)
callback(err);
return;
}
const geoJSON = {type: "FeatureCollection", features: JSON.parse(body).data.bikeRentalStations.map(station => ({
type: "Feature",
geometry: {type: "Point", coordinates: [station.lon, station.lat]},
properties: {
id: station.stationId,
name: station.name,
networks: station.networks.join()
}
}))}
const tileIndex = geojsonVt(geoJSON, {
maxZoom: 20,
buffer: 512
});
console.log(`${geoJSON.features.length} city bikes loaded from ${this.uri.href}`);
callback(null, tileIndex);
}.bind(this));
}
getTile(z, x, y, callback){
this.fetchBikeRentals(function(err, tileIndex){
if (err) {
console.log("Error while fetching citybike data:", err);
callback(err);
}
let tile = tileIndex.getTile(z, x, y);
if (tile === null){
tile = {features: []}
}
const data = Buffer.from(vtPbf.fromGeojsonVt({stations: tile}));
zlib.gzip(data, function (err, buffer) {
if (err){
callback(err);
return;
}
callback(null, buffer, {"content-encoding": "gzip"})
})
});
}
getInfo(callback){
callback(null, {
format: "pbf",
vector_layers: [{
description: "",
id: "stations"
}],
maxzoom: 20,
minzoom: 1,
name: "OTP Citybikes"
})
}
}
module.exports = OtpCityBikeSource
module.exports.registerProtocols = (tilelive) => {
tilelive.protocols['otpcitybikes:'] = OtpCityBikeSource
}