Created
January 24, 2018 20:46
-
-
Save pwin/4d503379ea84b91ba8e09877de221e88 to your computer and use it in GitHub Desktop.
Illustration of using javascript and AMCharts to access and present data from RDF data cube
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
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> | |
<html id="Scottish_Government" xmlns="http://www.w3.org/1999/xhtml" lang="en-GB" xml:lang="en-GB"> | |
<head> | |
<title>Golspie Half Hourly</title> | |
<!-- | |
This produces plots of half hourly consumption values | |
The dropdown for the buildings shows 45 consumers | |
--> | |
<link rel="stylesheet" href="/javascripts/jquery/css/redmond/jquery-ui-1.8.14.custom.css" type="text/css" media="all" /> | |
<script src="/javascripts/jquery/js/jquery-1.5.1.min.js" type="text/javascript"></script> | |
<script src="/javascripts/jquery/js/jquery-ui-1.8.14.custom.min.js" type="text/javascript"></script> | |
<script src="/javascripts/date.js" type="text/javascript"></script> | |
<!-- amcharts script--> | |
<!-- swf object (version 2.2) is used to detect if flash is installed and include swf in the page --> | |
<script type="text/javascript" src="/flash/swfobject.js"></script> | |
<!-- following scripts required for JavaScript version. The order is important! --> | |
<script type="text/javascript" src="/javascripts/amcharts/amcharts.js"></script> | |
<script type="text/javascript" src="/javascripts/amcharts/amfallback.js"></script> | |
<script type="text/javascript" src="/javascripts/amcharts/raphael.js"></script> | |
<script src="/javascripts/jquery/jquery.json-2.2.min.js" type="text/javascript"></script> | |
<script type="text/javascript" src="/javascripts/keyVariables.js"></script> | |
<style type="text/css"> | |
div#stats { | |
height: 70px; | |
} | |
#loading { | |
position: fixed; | |
top: 0; | |
left: 0; | |
z-index: 5000; | |
background-color: red; | |
font-size: 150%; | |
color: white; | |
padding: 2px; | |
} | |
div.stats_big, div.stats_small { | |
float: left; | |
padding: 10px 10px 10px 12px; | |
} | |
div.stats_big { | |
width: 150px; | |
font-size: 12px; | |
} | |
div.stats_small { | |
width: 100px; | |
font-size: 12px; | |
} | |
div.stats_bottom { | |
font-weight: bold; | |
font-size: 12px; | |
} | |
div.chart_container { | |
width: 800px; | |
height: 500px; | |
background-color: ivory; | |
float:left; | |
} | |
div.details_container { | |
width: 800px; | |
height: 50px; | |
background-color: ivory; | |
float:left; | |
} | |
div.stats_container { | |
width: 800px; | |
height: 150px; | |
background-color: ivory; | |
float:left; | |
} | |
</style> | |
<script type="text/javascript"> | |
jQuery.support.cors = true; | |
var buildingSelectList = ""; | |
String.prototype.left = function(n) { | |
return this.substring(0, n); | |
} | |
function formatDate(d,form){ | |
switch (form){ | |
case 1: | |
return Date.parse(d).toString('d MMM'); | |
break; | |
case 2: | |
return Date.parse(d).toString('d MMM yyyy'); | |
break; | |
} | |
} | |
function getQuery(query) { | |
var json = null; | |
$.ajax({ | |
'async': false, | |
'global': false, | |
'url': golspieQueries, | |
'dataType': "json", | |
'success': function (data) { | |
json = eval("data." + query); | |
}, | |
'error':function(jqXHR, textStatus, errorThrown){$("#err").empty().html('There was an error [' + textStatus + '] in accessing the data\n\n' + errorThrown);} | |
}); | |
return json; } | |
function buildingDataChunk(building, code, latitude, longitude){ | |
this.building = building; | |
this.code = code; | |
this.latitude = latitude; | |
this.longitude = longitude; | |
} | |
function getBuildingNames(id){ | |
var myURL = proxy + encodeURIComponent(getQuery(query4)); | |
var buildingData = new Array(); | |
$.ajax({ | |
'async': false, | |
'global': false, | |
'url': myURL, | |
'dataType': "json", | |
'success': function(data){ | |
//alert(data.results.bindings); | |
var aux = data.results.bindings; | |
var sel = '<select id="buildingselectbox">'; | |
for(var i=0;i<aux.length;i++){ | |
buildingData.push(new buildingDataChunk(aux[i].fn.value, aux[i].code.value, aux[i].latitude.value, aux[i].longitude.value)); | |
sel += '<option value="' + aux[i].code.value + '">' + aux[i].fn.value + '</option>'; | |
} | |
sel += '</select>'; | |
buildingSelectList = sel; | |
$(id).html(sel); | |
}, | |
'error':function(jqXHR, textStatus, errorThrown){$("#err").empty().html('There was an error [' + textStatus + '] in accessing the buildings data\n\n' + errorThrown);} | |
}); | |
return buildingData; | |
} | |
function getUtilityNames(id){ | |
//v = [{k:"electricity",v:"Electricity"},{k:"gas",v:"Gas"},{k:"water",v:"Water"}] | |
v = [{k:"electricity",v:"Electricity"},{k:"gas",v:"Gas"}] | |
var create = '<select id="utility">'; | |
for(var i=0;i<v.length;i++){ | |
create += '<option value="' + v[i].k + '">' + v[i].v + '</option>'; | |
} | |
create += '</select>'; | |
$(id).html(create); | |
} | |
function pad(n){ | |
return n<10 ? '0'+n : n | |
} | |
function ISODateString(d, pm) { | |
var t = pm ? "23:59:29" : "00:00:00" | |
var ISOds = d.getFullYear() + '-' + pad(d.getMonth()+1) + '-' + pad(d.getDate()) + 'T' + t ; | |
return ISOds; | |
} | |
function chartDataChunk(date, value){ | |
this.date = date; | |
this.value = value; | |
} | |
function dailyDataChunk(building, value){ | |
this.building = building; | |
this.value = value; | |
var x = parseFloat(value); | |
this.logValue = x > 0 ?Math.log(x) / Math.LN10 : 0; | |
} | |
function getUtilsForBuilding(id){ | |
$(id).html(""); | |
$("#details").empty(); | |
$("#periodAvgKWH").empty(); | |
$("#periodAvgCO2").empty(); | |
$("#totalKWH").empty(); | |
$("#totalCO2").empty(); | |
$("#err").empty(); | |
var building = ($("#buildingselectbox option:selected").text()); | |
var utility = ($("#utility option:selected").text()); | |
$("#chartContainer").html(""); | |
var D = new Date(); | |
D.setDate(D.getDate()-1); | |
var yesterday =ISODateString(D, true); | |
var D = new Date(); | |
D.setDate(D.getDate()-7); | |
var weekBefore = ISODateString(D, false);; | |
var fDate = ($("#fromDate").val()=="") ? weekBefore : $("#fromDate").val() + "T00:00:00"; | |
var tDate = ($("#toDate").val()=="") ? yesterday : $("#toDate").val() + "T23:59:29"; | |
var bldg = ($("#buildingselectbox"+ " option:selected").val()=="") ? "AB0134" : $("#buildingselectbox"+ " option:selected").val(); | |
var util = ($("#utility"+ " option:selected").val()=="") ? "electricity" : $("#utility"+ " option:selected").val(); | |
var query = " prefix xsd: <http://www.w3.org/2001/XMLSchema#> prefix gol: <http://cofog01.data.scotland.gov.uk/def/golspie/> prefix qb: <http://purl.org/linked-data/cube#> prefix buildingCode: <http://cofog01.data.scotland.gov.uk/id/facility/> prefix fn: <http://www.w3.org/2005/xpath-functions#> prefix util: <http://cofog01.data.scotland.gov.uk/def/golspie/> "; | |
query += " select (?dt as ?date) (max(?o) as ?value) where { "; | |
query += " ?slice gol:refBuilding buildingCode:" + bldg + " ; gol:reportDateTime ?dt ; qb:sliceStructure gol:sliceByHalfHour; qb:observation ?obs . ?obs gol:utilityConsumption ?o ; gol:refUtility util:" + util + " . "; | |
query += " filter ((?dt >= '" + fDate + "Z'^^xsd:dateTime) && (?dt <= '" + tDate + "Z'^^xsd:dateTime)) } group by ?obs ?slice ?dt order by ?dt limit 2000 " | |
var myURL = proxy + encodeURIComponent(query); | |
$("#q").html(query.replace(/</g,"%lt;").replace(/>/g,"$gt;")); | |
$.getJSON(myURL, | |
function(data){ | |
var aux = data.results.bindings; | |
var chartData = new Array(); | |
var total = 0; | |
if(typeof(aux[0].value) === 'undefined'){$("#err").empty().html("<b>No Data Available</b>"); return false;} | |
for(var i=0;i<aux.length;i++){ | |
total += parseFloat(aux[i].value.value); | |
chartData.push(new chartDataChunk(aux[i].date.value.replace(/T/," ").left(16)+"h", aux[i].value.value)); | |
} | |
var totalKWH = Math.round(total); | |
var avgKWH = Math.round(total/aux.length); | |
if(utility == 'Electricity'){ | |
var totalCO2 = Math.round(total * electricity_kwh2co2); | |
var avgCO2 = Math.round(total/aux.length * electricity_kwh2co2); | |
} | |
if(utility == 'Gas'){ | |
var totalCO2 = Math.round(total * gas_kwh2co2); | |
var avgCO2 = Math.round(total/aux.length * gas_kwh2co2); | |
} | |
$("#periodAvgKWH").html(avgKWH); | |
$("#periodAvgCO2").html(avgCO2); | |
$("#totalKWH").html(totalKWH); | |
$("#totalCO2").html(totalCO2); | |
plotSerialChart2(chartData); | |
$("#details").empty().html("<h3 style='text-align:center'>Half-hourly " + utility + " consumption (kWh) for " + building + " on " + formatDate(fDate.left(10),2) + "</h3>" ); | |
}); | |
} | |
function amChartInited(chart_id){ | |
alert(chart_id); | |
} | |
function plotSerialChart2(data){ | |
$("#chartContainer").html(""); | |
var chart = new AmCharts.AmSerialChart(); | |
chart.dataProvider = data; | |
chart.categoryField = "date"; | |
chart.marginTop = 25; | |
chart.marginLeft = 65; | |
chart.marginRight = 35; | |
chart.marginBottom = 120; | |
var catAxis = chart.categoryAxis; | |
catAxis.gridCount = data.length/12; | |
catAxis.labelRotation = 60; | |
var graph = new AmCharts.AmGraph(); | |
graph.valueField = "value" | |
graph.type = "column"; | |
graph.lineAlpha = 0; | |
graph.fillAlphas = 0.6; | |
chart.addGraph(graph); | |
chart.write("chartContainer"); | |
} | |
function clearDates(){ | |
$("#fromDate").val(""); | |
$("#toDate").val(""); | |
return true; | |
} | |
function syncDates(){ | |
$("#toDate").val($("#fromDate").val()); | |
} | |
$(document).ready(function(){ | |
clearDates(); | |
$("#fromDate").datepicker({changeMonth: true, changeYear: true, constrainInput: true, minDate: new Date(2012,0,1), maxDate: -1, dateFormat:'yy-mm-dd', defaultDate:-3}); | |
$("#fromDate").datepicker('setDate', -3); | |
$('#loading').bind('ajaxSend', function() {var n = $(this); n.show();}) | |
$('#loading').bind('ajaxComplete', function() {var n = $(this); n.hide()}); | |
var buildingData = getBuildingNames("#building"); | |
getUtilityNames("#util"); | |
$("#go").click(function(){getUtilsForBuilding("#resultTable");}) | |
$("#clear").click(function(){clearDates();}) | |
$("#buildingselectbox").val("AB0103"); | |
$("#building").change(function(){getUtilsForBuilding("#resultTable");}); | |
$("#utility").change(function(){if($("#utility").val()=='gas'){ | |
var tempVal = $("#buildingselectbox").val(); | |
if(tempVal== 'AB0032' ||tempVal== 'AB0127'){ | |
alert('There is no gas meter for this building.'); | |
$("#utility").val('electricity'); | |
$("#buildingselectbox").val(tempVal); | |
return false; | |
} | |
$("#buildingselectbox option[value='AB0032']").remove();// Europa Building | |
$("#buildingselectbox option[value='AB0127']").remove();// Highlander House | |
} | |
else { | |
var tempVal = $("#buildingselectbox").val(); | |
$("#building").empty().html(buildingSelectList); | |
$("#buildingselectbox").val(tempVal); | |
}; | |
getUtilsForBuilding("#resultTable"); | |
}); | |
$("#toDate").val($("#fromDate").val()); | |
$("#fromDate").change(function(){$("#toDate").val($("#fromDate").val());getUtilsForBuilding("#resultTable");}); | |
getUtilsForBuilding("#resultTable"); | |
}); | |
</script> | |
</head> | |
<body> | |
<div><span id="building"> </span> <span>Date: <input type="text" length="12" id="fromDate"><input type="hidden" length="12" id="toDate"></span> | |
Utility: <span id="util"> </span> | |
</div> | |
<div id="err"> </div> | |
<hr/> | |
<div id="loading" style="display:none">Loading....</div> | |
<div id="chartContainer" class="chart_container"> </div> | |
<div id="details" class="details_container"> </div> | |
<div class="stats_container"> | |
<div id="stats"> | |
<div class="stats_big"> | |
<div class="stats_head"> | |
½ Hour Average kWh | |
</div> | |
<div id="periodAvgKWH" class="stats_bottom"> | |
</div> | |
</div> | |
<div class="stats_big"> | |
<div class="stats_head"> | |
½ Hour Average Kg CO<sub>2</sub> | |
</div> | |
<div id="periodAvgCO2" class="stats_bottom" > | |
</div> | |
</div> | |
<div class="stats_big"> | |
<div class="stats_head"> | |
Total kWh | |
</div> | |
<div id="totalKWH" class="stats_bottom" > | |
</div> | |
</div> | |
<div class="stats_big"> | |
<div class="stats_head"> | |
Total Kg CO<sub>2</sub> | |
</div> | |
<div id="totalCO2" class="stats_bottom"> | |
</div> | |
</div> | |
</div> | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment