This repository was archived by the owner on Aug 26, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrouting.js
101 lines (93 loc) · 2.31 KB
/
routing.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
$('#error').hide()
function error(message){
if(!message){
$('#error').html('')
$('#error').hide()
}
else{
$('#error').html(message)
$('#error').show()
}
}
function firstN(list, n){
counter = 0
result = []
for(item of list){
result.push(item)
counter++
if(counter==n) break
}
return result
}
function guessStation(input){
query = input.val()
$.ajax({
url: 'https://transport.rest/locations?query='+query,
dataType: 'json',
success: function(res){
console.log(res[0].id)
if(res.length>0){
if(!input.next('input').attr('value')){
input.attr('value', res[0].id)
input.val(res[0].name)
}
}
else{
input.val(null);
}
},
error: function(data){
input.val(query)
}
})
}
function getRoute(from, to){
$.ajax({
url: 'https://transport.rest/routes?from='+from+'&to='+to,
dataType: 'json',
success: function(res){
if(!res||res.length==0) error('Keine Routen gefunden.')
},
error: function(data){
error('Fehler beim Abfragen der Routen.')
}
})
}
function addAutocomplete(sel){
$(sel).autocomplete({
serviceUrl: 'https://transport.rest/locations',
paramName: 'query',
params: {
results: 50
},
minChars: 3,
transformResult: function(response) {
return {
suggestions: $.map(firstN(_.filter($.parseJSON(response), (o) => (o.products && (o.products.subway||o.products.suburban))), 5), function(dataItem) {
return { value: dataItem.name, data: dataItem.id}
})
}
},
onSelect: function(suggestion) {
$(sel).attr('value', suggestion.data);
if(sel=="#from-station") $('#to-station').focus()
else $('#submit').focus()
}
})
}
addAutocomplete('#from-station')
addAutocomplete('#to-station')
$('.station').focusout(function(){
if(!$(this).attr('value')){
guessStation($(this));
}
})
$('#submit').click(() => {
error(null)
if(!+$('#from-station').attr('value')||!+$('#to-station').attr('value')) error('Bitte geben Sie einen gültigen Start- und Zielbahnhof an.')
else{
from = +$('#from-station').attr('value')
to = +$('#to-station').attr('value')
getRoute(from, to)
}
})