【问题标题】:High Charts windrose from API data (JSON)来自 API 数据 (JSON) 的 Highcharts windrose
【发布时间】:2016-04-07 11:47:04
【问题描述】:

我在这里很新(以及一般的网络开发),所以请原谅我一直存在的任何误用......我正在尝试创建一个基本的风玫瑰图,其中包含从 MesoWest Mesonet 返回的数据(以 JSON 格式) 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>

感谢您在这方面的任何指导,谢谢!!! -会

【问题讨论】:

  • javascript 控制台有错误吗?
  • 另外,您能否发布您的 windDataJSON 对象的内容,因为它在填充它的 for 循环之后查找?
  • 我向@HalvorStrand 道歉,但正如我所提到的,我在这方面是个新手。你是什​​么意思的javascript控制台?它在哪里?
  • @jlbriggs,我也不确定该对象是否完全正确填充。通常使用的完整查询是:api.mesowest.net/v2/stations/… 我从发布在 MesoWest API 示例页面上的示例小部件中编写了这个 js。也许我没有在我的循环中完全正确地填充对象?这是我在这个媒体上的第一次尝试。
  • 1) 控制台内置于您的浏览器中,如果有任何 javascript 错误,它们将在那里显示。 Google 如何查看特定浏览器的控制台。

标签: javascript json api highcharts weather


【解决方案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 看到这一切。祝你好运!

【讨论】:

    猜你喜欢
    • 2014-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多