Browse Source

Render: Start adding render method for a temperature chart

master
Nathan Bergey 6 years ago
parent
commit
81a6c9e252
  1. 50
      src/data.js
  2. 5
      src/index.js
  3. 33
      src/render.js
  4. 7
      src/style.sass

50
src/data.js

@ -0,0 +1,50 @@
var d3 = require('d3')
export function readxml(xmldoc) {
let forcast = xmldoc.childNodes[0]
let data = forcast.children[1]
// Time
let times = data.getElementsByTagName('time-layout')[0]
var startTimes = []
for (let time of times.getElementsByTagName('start-valid-time')) {
let date = new Date(time.textContent)
startTimes.push(date)
}
var endTimes = []
for (let time of times.getElementsByTagName('end-valid-time')) {
let date = new Date(time.textContent)
endTimes.push(date)
}
// Temperature
var temperatures = []
for (let temp_type of data.getElementsByTagName('temperature')) {
if (temp_type.attributes.type.nodeValue === 'hourly') {
for (let temp of temp_type.getElementsByTagName('value')) {
let degC = (parseFloat(temp.textContent) - 32) * (5.0/9.0)
temperatures.push(degC)
}
}
}
// Map
let nElements = startTimes.length
var forcastData = []
for (var i = 0; i < nElements; i++) {
let midtimeScale = d3.scaleTime()
.domain([0, 1])
.range([startTimes[i], endTimes[i]])
let midpointTime = midtimeScale(0.5)
forcastData.push({
'date': midpointTime,
'temp': temperatures[i]
})
}
return {
'startTimes': startTimes,
'endTimes': endTimes,
'temperature': forcastData
}
}

5
src/index.js

@ -1,9 +1,12 @@
var d3 = require('d3')
import {readxml} from './data.js'
import {render} from './render.js'
let canvas = d3.select('svg')
//const url = 'https://forecast.weather.gov/MapClick.php?lat=39.9243509&lon=-75.1696126&FcstType=digitalDWML'
const url = '/forcast.xml'
d3.xml(url).then(function(xmldoc) {
console.log(xmldoc)
let data = readxml(xmldoc)
render(canvas, data)
})

33
src/render.js

@ -0,0 +1,33 @@
var d3 = require('d3')
export function render(canvas, data) {
let xWidth = canvas.node().getBoundingClientRect().width
let yHeight = canvas.node().getBoundingClientRect().height
let xMargin = 50
let yMargin = 25
let nElements = data.startTimes.length
let beginTime = new Date(
data.startTimes[0].getFullYear(),
data.startTimes[0].getMonth(),
data.startTimes[0].getDate(),
0,0,0
)
let xRange = d3.scaleTime()
.domain([beginTime, data.endTimes[nElements - 1]])
.range([xMargin, xWidth])
let yRange = d3.scaleLinear()
.domain([-15, 45])
.range([yHeight - yMargin, 0])
let line = d3.line()
.x(function(d) { return xRange(d.date) })
.y(function(d) { return yRange(d.temp) })
.curve(d3.curveBasis)
canvas.append('path')
.data([data.temperature])
.attr('class', 'data')
.attr('d', line)
}

7
src/style.sass

@ -40,3 +40,10 @@ h1.title
.title .city
font-weight: bold
path, line
fill: none
path.data
stroke: #f00
stroke-width: 2px
Loading…
Cancel
Save