-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
75 lines (61 loc) · 2.02 KB
/
script.js
File metadata and controls
75 lines (61 loc) · 2.02 KB
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
'use strict';
// Some fixed test values:
//const postcode = 'N4 2DF';
//const lat = 51.56515;
//const lon = -0.10520;
const myFormElement = document.querySelector('form');
const myResultsElement = document.querySelector('#results');
function handleForm() {
const myFormData = new FormData(myFormElement);
const myData = Object.fromEntries(myFormData);
const postcode = myData["postcode"];
const radius = myData["radius"]; // metres, 200 is default
let lat, lon;
/*
fetch(`https://api.tfl.gov.uk/StopPoint/Meta/StopTypes`)
.then((response) => {
return response.json();
})
.then((response) => {
console.log(response);
});
*/
/*
StopTypes of interest?
NaptanMetroStation
NaptanRailStation
*/
// const radius = 1000;
const stopTypes = 'NaptanMetroStation,NaptanRailStation';
fetch(`https://api.postcodes.io/postcodes/${postcode}`)
.then((response) => {
return response.json();
})
.then((response) => {
lat = response["result"]["latitude"];
lon = response["result"]["longitude"];
})
.then(() => {
// Probably shouldn't nest like this, find a better structure.
fetch(`https://api.tfl.gov.uk/StopPoint/?lat=${lat}&lon=${lon}&stopTypes=${stopTypes}&radius=${radius}`)
.then((response) => {
return response.json();
})
.then((response) => {
//console.log(response);
const stopPointsArray = response["stopPoints"];
let html = `Rail station(s) within ${radius} metres:<ul>`;
for (const element of stopPointsArray) {
const commonName = element["commonName"];
const distance = Math.round(element["distance"]);
html += `<li>${commonName} (~${distance}m away)</li>`;
}
html += '</ul>';
myResultsElement.innerHTML = html;
});
});
}
myFormElement.addEventListener("submit", (event) => {
handleForm();
event.preventDefault();
});