来自API数据(JSON)的高图表windrose

时间:2016-01-03 20:47:19

标签: javascript json api highcharts weather

我在这里很新(以及一般的网络开发),所以请原谅我长期存在的任何误用......我正在尝试使用MesoWest Mesonet返回的数据(以JSON格式)创建一个基本的windrose图API服务。我正在使用HighCharts(或尝试),并且不能完全使用它。也许这是由于我从API本身获取数据的方法,因为我在这方面是一个完全的业余爱好者。以下是Javascript代码,后跟页面的HTML。有人可以看看,让我知道我做错了什么?当我尝试加载它时,页面上没有显示任何内容。另外,如果您对MesoWest的API调用的具体情况感到好奇,就像我在这里使用的那样,请参阅http://mesowest.org/api/docs/ .js脚本:

var windrose = {
divname: "windrosediv",
tkn: "eecfc0259e2946a68f41080021724419",
load:function()
{
    console.log('loading')
    if (!window.jQuery) {
    var script = document.createElement("script");
    script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
    script.type = 'text/javascript';
    document.getElementByTagName("head")[0].appendChild(script);
    setTimeout(pollJQuery, 100)
    return
 }
 this.div = $("#"+this.divname);
 this.request('WBB');
 },
 pollJQuery:function()
 {
    if (!window.jQuery) {
       setTimeout(pollJQuery,100);
    } else {
        load();
    }
  },
  request:function(stn){
     console.log("making a request")
     $.getJSON(http://api.mesowest.net/v2/stations/nearesttime?callback=?',
     {
       stid:stn,
       within:1440,
                   units:'english',
       token:windrose.tkn
      }, this.receive);
  },
  receive:function (data)
     {
      console.log(data,windrose);
      stn = data.STATION[0]
      dat = stn.OBSERVATIONS
      spd += Math.round(dat.wind_speed_value_1.value)
      dir += dat.wind_direction_value_1.value
     windDataJSON = [];
for (i = 0; i < dir.length; i++) {
    windDataJSON.push([ dir[i], spd[i] 
    ]); 
        },
     }
  $(function () {
    var categories = ['0', '45', '90', '135', '180', '225', '270', '315'];
$('#container').highcharts({
      series: [{
        data: windDataJSON
    }],
    chart: {
        polar: true,
        type: 'column'
    },
    title: {
        text: 'Wind Rose'
    },
    pane: {
        size: '85%'
    },
    legend: {
        align: 'right',
        verticalAlign: 'top',
        y: 100,
        layout: 'vertical'
    },
    xAxis: {
        min: 0,
        max: 360,
        type: "",
        tickInterval: 22.5,
        tickmarkPlacement: 'on',
        labels: {
            formatter: function () {
                return categories[this.value / 22.5] + '°';
            }
        }
    },
    yAxis: {
        min: 0,
        endOnTick: false,
        showLastLabel: true,
        title: {
            text: 'Frequency (%)'
        },
        labels: {
            formatter: function () {
                return this.value + '%';
            }
        },
        reversedStacks: false
    },
    tooltip: {
        valueSuffix: '%'
    },
    plotOptions: {
        series: {
            stacking: 'normal',
            shadow: false,
            groupPadding: 0,
            pointPlacement: 'on'
        }
    }
});

});

HTML:

<!DOCTYPE html>
<html>

<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>
<script src="https://code.highcharts.com/modules/data.js">`enter code     </script>
<script src="https://code.highcharts.com/modules/exporting.js">    </script>

<div id="container" style="min-width: 420px; max-width: 600px; height: 400px; margin: 0 auto"></div>
<p class="ex">
<script type="text/javascript" src="http://home.chpc.utah.edu/~u0675379/apiDemos/windTest.js"></script>
</p>
</html>

我很感谢这方面的任何指导,谢谢! - 将

1 个答案:

答案 0 :(得分:1)

@ W.Howard,我认为这里的问题是你如何处理和准备API的JSON响应。请考虑以下JavaScript来检索和解析数据:

/*
 * Helper function
 * scalarMultiply(array, scalar)
 */
function scalarMultiply(arr, scalar) {
    for (var i = 0; i < arr.length; i++) {
        arr[i] = arr[i] * scalar;
    }
    return arr;
}


/*
 * getQuery(station, api_token)
 */
    function getQuery(station, mins, api_token) {

        $.getJSON('http://api.mesowest.net/v2/stations/timeseries?callback=?', {
                /* Specify the request parameters here */
                stid: station,
                recent: mins, /* How many mins you want */
                obtimezone: "local",
                vars: "wind_speed,wind_direction,wind_gust",
                jsonformat: 2, /* for diagnostics */
                token: api_token
            },
            function(data) {

                try {
                    windSpeed = data.STATION[0].OBSERVATIONS.wind_speed_set_1;
                    windDir = data.STATION[0].OBSERVATIONS.wind_direction_set_1;
                    windGust = data.STATION[0].OBSERVATIONS.wind_gust_set_1;
                } catch (err) {
                    console.log("Data is invalid. Check your API query");
                    console.log(this.url);
                    exit();
                }

                /* Convert from knots to mph */
                windSpeed = scalarMultiply(windSpeed, 1.15078);
                //windGust = scalarMultiply(windGust, 1.15078);

                /* Create and populate array for plotting */
                windData = [];
                for (i = 0; i < windSpeed.length; i++) {
                    windData.push([windDir[i], windSpeed[i]]);
                }

                /* Debug */
                // console.log(windData);
                console.log(this.url);

                plotWindRose(windData, mins);
            })
    };

我们现在拥有的是具有风向和风速的二维阵列,我们可以将其传递给绘图功能。以下是更新的绘图功能:

/*
 * Plot the wind rose
 * plotWindRose([direction, speed])
 */
    function plotWindRose(windData, mins) {

        /*
         * Note:
         * Because of the nature of the data we will accept the HighCharts Error #15.
         * --> Highcharts Error #15 (Highcharts expects data to be sorted).
         *     This only results in a performance issue.
         */
        var categories = ["0", "45", "90", "135", "180", "225", "270", "315"];

        $('#wind-rose').highcharts({
            series: [{
                name: "Wind Speed",
                color: '#cc3000',
                data: windData
            }],
            chart: {
                type: 'column',
                polar: true
            },
            title: {
                text: 'Wind Direction vs. Frequency (Last ' + mins/60. + ' hours)'
            },
            pane: {
                size: '90%',
            },
            legend: {
                align: 'right',
                verticalAlign: 'top',
                y: 100,
                text: "Wind Direction"
            },
            xAxis: {
                min: 0,
                max: 360,
                type: "",
                tickInterval: 45,
                tickmarkPlacement: 'on',
                labels: {
                    formatter: function() {
                        return categories[this.value / 45] + '\u00B0';
                    }
                }
            },
            yAxis: {
                min: 0,
                endOnTick: false,
                showLastLabel: true,
                title: {
                    text: 'Frequency (%)'
                },
                labels: {
                    formatter: function() {
                        return this.value + '%';
                    }
                },
                reversedStacks: false
            },
            tooltip: {
                valueSuffix: '%'
            },
            plotOptions: {
                series: {
                    stacking: 'normal',
                    shadow: false,
                    groupPadding: 20,
                    pointPlacement: 'on'
                }
            }
        });
    }

你可以在https://gist.github.com/adamabernathy/eda63f14d79090ab1ea411a8df1e246e看到这一切。祝你好运!