Created
September 5, 2020 14:49
-
-
Save matthieugd/e15136a48ccfc232ed06bf5dadbdc9ca to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<script> | |
let userLatitude = parseFloat('45.532032'); | |
let userLongitude = parseFloat('-73.595368'); | |
let stationsInfosEndpoint = 'https://api-core.bixi.com/gbfs/en/station_information.json'; | |
let stationsStatusEndpoint = 'https://api-core.bixi.com/gbfs/en/station_status.json'; | |
let xhr = new XMLHttpRequest(); | |
xhr.open('GET', stationsInfosEndpoint, false); | |
xhr.send(null); | |
let stationsinfosResponse = JSON.parse(xhr.responseText); | |
let stationsinfos = stationsinfosResponse.data.stations; | |
xhr = new XMLHttpRequest(); | |
xhr.open('GET', stationsStatusEndpoint, false); | |
xhr.send(null); | |
let stationsstatusResponse = JSON.parse(xhr.responseText); | |
let stationsstatus = stationsstatusResponse.data.stations; | |
let listOfStations = []; | |
for (let i = 0; i < stationsinfos.length; i++) | |
{ | |
let stationInfo = stationsinfos[i]; | |
let id = stationInfo.station_id; | |
let stationStatus = stationsstatus.find(s => s.station_id == id); | |
if(stationStatus != null | |
&& stationStatus.is_installed == 1 | |
&& stationStatus.is_renting == 1 | |
&& stationStatus.num_bikes_available > 0) | |
{ | |
let stationLatitude = parseFloat(stationInfo.lat); | |
let stationLongitude = parseFloat(stationInfo.lon); | |
let distance = haversineDistance(stationLatitude, stationLongitude, userLatitude, userLongitude, false); | |
let station = { | |
"id" : id, | |
"name": stationInfo.name, | |
"distance": distance, | |
"bikes": stationStatus.num_bikes_available | |
} | |
listOfStations.push(station); | |
} | |
} | |
listOfStations.sort((s1, s2) => parseFloat(s1.distance) - parseFloat(s2.distance)); | |
let nearMe = JSON.stringify(listOfStations.slice(0,4)); | |
document.write(nearMe); | |
function haversineDistance(lat1, lon1, lat2, lon2, isMiles = false) | |
{ | |
const toRadian = angle => (Math.PI / 180) * angle; | |
const distance = (a, b) => (Math.PI / 180) * (a - b); | |
const RADIUS_OF_EARTH_IN_KM = 6371; | |
const dLat = distance(lat2, lat1); | |
const dLon = distance(lon2, lon1); | |
lat1 = toRadian(lat1); | |
lat2 = toRadian(lat2); | |
// Haversine Formula | |
const a = | |
Math.pow(Math.sin(dLat / 2), 2) + | |
Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2); | |
const c = 2 * Math.asin(Math.sqrt(a)); | |
let finalDistance = RADIUS_OF_EARTH_IN_KM * c; | |
if (isMiles) { | |
finalDistance /= 1.60934; | |
} | |
return finalDistance; | |
} | |
</script> | |
</head> | |
<body></body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment