JavaScript模块化编程实例——天气预报


良好的习惯是成功的一半。今天总结一个JavaScript模块化编程实例学习交流,这个例子是之前没有按照模块化概念来写的,今天把它按照AMD规范重新封装了一个js文件,主要实现天气预报数据的解析与地图绘制。天气API采用百度API集市提供的天气预报API。

1、weatherUtil.js

weatherUtil.js是解析天气预报数据模块,完成数据解析和图层绘制两个工作,代码如下,熟悉requirejs规范和基本js知识很容易理解。

define(['leaflet'], function(){
    /**
     * 解析天气预报,返回每个城市天气描述对象
     * @param weatherObj
     * @returns {{city: *, cityLat: *, cityLon: (_options.lon|*|sdl_path.lon), temperature_now: (.copyState.tmp|*|tmp), temperature_max: *, temperature_min: *, weather_now: *}}
     * @private
     */
    function _parseWeather(weatherObj){

        var aqi = weatherObj.aqi; //空气质量
        var basic = weatherObj.basic;//城市信息
        var now = weatherObj.now;//天气实况
        var dailyForecast = weatherObj.daily_forecast;//逐日预报
        var hourForecast = weatherObj.hourForecast;//3小时预报
        var suggestion = weatherObj.suggestion;//生活指数
        // basic:城市基本信息
        var city = basic.city;
        var cityLat = basic.lat;
        var cityLon = basic.lon;
        var update = basic.update;//更新时间
        // aqi:空气质量指数
        //var aqi_index = aqi.city.aqi;// 空气质量指数
        //var pm25 = aqi.city.pm25;// PM2.5 1小时平均值(ug/m³)
        //var qlty = aqi.city.qlty;// 空气质量类别
        // 实况天气
        var now_weather = now.cond.txt;
        var fl = now.fl;// 体感温度
        var wind_spd_now = now.wind.spd;// 风速(km/h)
        var wind_sc_now = now.wind.sc;// 风力等级
        var wind_deg_now = now.wind.deg;// 风向(角度)
        var wind_dir_now = now.wind.dir;// 风向(方向)
        var pcpn_now = now.pcpn;// 降雨量
        var hum_now = now.hum;// 湿度(%)
        var pres_now = now.pres;// 气压
        var tmp_now = now.tmp;// 温度
        var vis_now = now.vis;// 能见度

        // 天气预报:dailyForecast
        var day0 = dailyForecast[0];// 今天
        var day_sr = day0.astro.sr;// 日出时间
        var day_ss = day0.astro.ss;// 日落时间
        var cond_day = day0.cond.txt_d;// 白天天气描述
        var cond_night = day0.cond.txt_n;// 夜间天气描述
        var tmp_max = day0.tmp.max;// 最高气温
        var tmp_min = day0.tmp.min;// 最低气温
        var wind_spd_day0 = day0.wind.spd;
        var wind_sc_day0 = day0.wind.sc;
        var wind_dir_day0 = day0.wind.dir;

        return {
            city : city,//城市名称
            cityLat : cityLat,//城市纬度
            cityLon : cityLon,//城市经度
            temperature_now : tmp_now,//当前温度
            temperature_max : tmp_max,//今日最高温度
            temperature_min : tmp_min,//今日最低温度
            weather_now : now_weather//当前天气
        }
    };
    /**
     * 绘制天气标记
     * @param array:天气预报数组
     * @returns {*}:天气预报图层
     * @private
     */
    function _drawWeatherMarker(array){

        var layer = L.LayerGroup.collision({margin : 10});
        array.forEach(function(obj){
            var weatherIcon = L.icon({
                iconUrl : _getIconUrl(obj.weather_now),
                iconSize : [32, 32],
                iconAnchor : [0, 0],
                popupAnchor : [12, 7]
            });
            var marker = L.marker(L.latLng(obj.cityLat, obj.cityLon), {
                icon : weatherIcon
            }).bindPopup("<h2>" + obj.city + "</h2>" + "</br>" + "<h2>" + obj.weather_now + "</h2>");
            layer.addLayer(marker);
        });
        return layer;
    };

    /**
     * 根据天气获取对应描述图片
     * @param weather
     * @returns {*}
     * @private
     */
    function _getIconUrl(weather){
        var iconUrl;
        switch(weather){
            case '晴' :
                iconUrl = 'images/weather/government/晴.png';
                break;
            case '多云' :
                iconUrl = 'images/weather/government/多云.png';
                break;
            case '少云' :
                iconUrl = 'images/weather/government/多云.png';
                break;
            case '晴间多云' :
                iconUrl = 'images/weather/government/多云.png';
                break;
            case '阴' :
                iconUrl = 'images/weather/government/阴.png';
                break;
            case '阵雨' :
                iconUrl = 'images/weather/government/阵雨.png';
                break;
            case '强阵雨' :
                iconUrl = 'images/weather/government/阵雨.png';
                break;
            case '雷阵雨' :
                iconUrl = 'images/weather/government/雷阵雨.png';
                break;
            case '强雷阵雨' :
                iconUrl = 'images/weather/government/雷阵雨.png';
                break;
            case '雷阵雨伴有冰雹' :
                iconUrl = 'images/weather/government/雷阵雨伴有冰雹.png';
                break;
            case '小雨' :
                iconUrl = 'images/weather/government/小雨.png';
                break;
            case '中雨' :
                iconUrl = 'images/weather/government/中雨.png';
                break;
            case '大雨' :
                iconUrl = 'images/weather/government/大雨.png';
                break;
            case '极端降雨' :
                iconUrl = 'images/weather/government/大雨.png';
                break;
            case '毛毛雨/细雨' :
                iconUrl = 'images/weather/government/小雨.png';
                break;
            case '暴雨' :
                iconUrl = 'images/weather/government/暴雨.png';
                break;
            case '大暴雨' :
                iconUrl = 'images/weather/government/大暴雨.png';
                break;
            case '特大暴雨' :
                iconUrl = 'images/weather/government/特大暴雨.png';
                break;
            case '冻雨' :
                iconUrl = 'images/weather/government/冻雨.png';
                break;
            case '小雪' :
                iconUrl = 'images/weather/government/小雪.png';
                break;
            case '中雪' :
                iconUrl = 'images/weather/government/中雪.png';
                break;
            case '大雪' :
                iconUrl = 'images/weather/government/大雪.png';
                break;
            case '暴雪' :
                iconUrl = 'images/weather/government/暴雪.png';
                break;
            case '雨夹雪' :
                iconUrl = 'images/weather/government/雨夹雪.png';
                break;
            case '雨雪天气' :
                iconUrl = 'images/weather/government/雨夹雪.png';
                break;
            case '阵雨夹雪' :
                iconUrl = 'images/weather/government/雨夹雪.png';
                break;
            case '阵雪' :
                iconUrl = 'images/weather/government/阵雪.png';
                break;
            case '薄雾' :
                iconUrl = 'images/weather/government/雾.png';
                break;
            case '雾' :
                iconUrl = 'images/weather/government/雾.png';
                break;
            case '霾' :
                iconUrl = 'images/weather/government/霾.png';
                break;
            case '扬沙' :
                iconUrl = 'images/weather/government/扬沙.png';
                break;
            case '浮尘' :
                iconUrl = 'images/weather/government/浮尘.png';
                break;
            case '沙尘暴' :
                iconUrl = 'images/weather/government/强沙尘暴.png';
                break;
            case '强沙尘暴' :
                iconUrl = 'images/weather/government/强沙尘暴.png';
                break;
            case '未知' :
                iconUrl = 'images/weather/government/无.png';
                break;
            default :
                iconUrl = 'images/weather/government/无.png';
                break;
        }
        return iconUrl;

    }

    /**
     * 封装
     */
    return {
        parseWeather : _parseWeather,
        drawWeatherMarker : _drawWeatherMarker
    }

})

2、调用

main.js中调用如下:

require(['jquery', 'weatherUtil'], function($, weatherUtil){

        //加载天气预报
        $.ajax({
            url : webRoot + "/servlet/getWeather",
            type : 'get',
            dataType : 'json',
            async : true,
            success : function(result){
                //解析天气预报数据
                var array = [];
                result.forEach(function(obj){
                    var weatherInd = obj['HeWeather data service 3.0'][0];
                    array.push(weatherUtil.parseWeather(weatherInd));
                });
                //绘制天气标记
                var weatherLayer = weatherUtil.drawWeatherMarker(array).addTo(mainmap);
                layerControl.addOverlay(weatherLayer, '江西省天气预报');
            },
            failure : function(data){

            }
        })
});

3、实现效果

实现效果如下图所示,另外使用了leaflet的聚合图层(即上述代码中的collision图层),避免了图标的堆叠。
这里写图片描述
目前,前端数据接入及可视化表达做的差不多了,后面应该多放精力在算法和模型上面了,每天坚持写代码2-4小时,看论文总结,看书总结。


4、总结

javascript模块化总结到现在为止了,这个过程中也加深了自己的理解,在以后的设计和编码中都要运用这种方法,带来的好处是显而易见的。推荐所有学习前端开发的以及想学习前端开发的都采用这种规范哈。最后,我自己总结的三篇文章链接:
[1] JavaScript模块化编程
[1] 深入理解JavaScript模块化编程:RequireJS
[3] JavaScript模块化编程实例——天气预报

转载自:https://blog.csdn.net/giser_whu/article/details/51186907

You may also like...