Metro Example
New API - LUKE MASON
by Alex Azuero
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.min.css">
<label>Bus Stop Station: </label><select class="form-control" id="bStops">
<option value="" disabled selected>Select a station</option>
</select>
<!-- This div should contain a live updating copy of the selected station -->
<table class="table table-striped" id="status">
</table>
JavaScript
var apiKey = '11070c26c3224c15bfef321427708beb';
var bStops = 'https://api.wmata.com/Bus.svc/json/jStops?&api_key=11070c26c3224c15bfef321427708beb';
var next;
var select = $('#bStops');
var $status = $('#status');
$('#bStops').change(function() {
getStationStatus();
clearTimeout(next);
});
//get the list
$.ajax({
url: bStops,
// tell jQuery we're expecting JSONP
dataType: "jsonp",
// work with the response
success: function( response ) {
if(typeof(response !== 'undefined') ){
var selectTemp = select.clone();
$.each(response.Stops,function( index, value ) {
selectTemp.append(
$("<option></option>")
.attr("value",value.StopID) //Gets the stopId
.text(value.Routes)
);
});
select.html(selectTemp.html()).chosen();
}
}
});
//get the selected station status
var getStationStatus = function(){
var bStopSel = select.val();
//alert(bStopSel);
var status = 'https://api.wmata.com/NextBusService.svc/json/jPredictions?StopID='+bStopSel+'&api_key='+apiKey;
//alert(status);
$.ajax({
url: status,
// tell jQuery we're expecting JSONP
dataType: "jsonp",
// work with the response
success: function( response ) {
//console.log(response.Predictions);
//console.log(response);
if(typeof(response !== 'undefined') ){
$statusTemp = $('<table></table>');
$.each(response.Predictions,function( index, value ) {
console.log(value);
$statusTemp.append('<tr><td> '+value.RouteID+'</td><td> '+value.Minutes+' </td></tr>');
});
$status.html( $statusTemp.html());
}
next = setTimeout(function(){getStationStatus()}, 10000);
}
});
} ;