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>Station: </label><select class="form-control" id="stations"> 
    <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>

CSS

#status {
    margin-top:2em;
}

JavaScript

var apiKey = '11070c26c3224c15bfef321427708beb';
var stations = 'https://api.wmata.com/Rail.svc/json/jStations?&api_key=11070c26c3224c15bfef321427708beb';
var next;
var $select = $('#stations');
var $status = $('#status');

$('#stations').change(function() {
 getStationStatus();
 clearTimeout(next);
});


//get the list
$.ajax({
    url: stations,
    // 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.Stations,function( index, value ) {
               $selectTemp.append(
                  $("<option></option>")
                 .attr("value",value.Code)
                 .text(value.Name)
                 ); 
            });
            $select.html($selectTemp.html()).chosen();
        }
    }
});

//get the selected station status
var getStationStatus = function(){
        var station = $select.val();
        var status = 'https://api.wmata.com/StationPrediction.svc/json/GetPrediction/'+station+'?api_key='+apiKey;
    $.ajax({
    url: status,
    // tell jQuery we're expecting JSONP
    dataType: "jsonp", 
    // work with the response
    success: function( response ) {
        if(typeof(response !== 'undefined') ){
            $statusTemp = $('<table></table>');
            $.each(response.Trains,function( index, value ) {
               $statusTemp.append('<tr><td> '+value.Line+' </td><td> '+value.Destination+' </td><td> '+ value.Min+' </td></tr>');
            });
            $status.html( $statusTemp.html());
        }
        next = setTimeout(function(){getStationStatus()}, 10000);
    }
});
}