Echarts中使用Ajax请求武汉疫情数据绘制全国疫情分布地图

image description

Echarts中使用Ajax请求武汉疫情数据绘制全国疫情分布地图

2020.2.4更新

完整的项目工程地址https://github.com/Arithmeticjia/wuhan

更新了部分前端代码,按照数据区间绘制地图 

上一篇文章讲了如何爬取丁香园的疫情数据,但是呢,由于是使用Django直接返回的页面数据,不具有通用性,现在打算把前后端分离开,在前端直接使用js请求加载Echarts地图

后端使用的是Django

# 返回json
def china_wuhan_virus(request):
    if request.method == 'GET':
        import requests
        from bs4 import BeautifulSoup
        from selenium import webdriver

        target = 'https://3g.dxy.cn/newh5/view/pneumonia?scene=2&clicktime=1579579384&enterid=1579579384&from=groupmessage&isappinstalled=0'
        req = requests.get(url=target)
        req.encoding = 'urf-8'
        html = req.text
        option = webdriver.ChromeOptions()
        option.add_argument('headless')  # 设置option,后台运行
        driver = webdriver.Chrome(chrome_options=option)
        driver.get(target)
        js = "var q=document.documentElement.scrollTop=1500"
        driver.execute_script(js)
        selenium_page = driver.page_source
        driver.quit()
        soup = BeautifulSoup(selenium_page, 'html.parser')
        all_info = soup.find('div', {'class': 'areaBox___3jZkr'})
        # 每个省
        protocols = all_info.find_all('div')
        data = {}
        for i in protocols:
            try:
                first = i.find('div', {'class': 'areaBlock1___3V3UU'})
                content = first.find_all('p')
                name = content[0].get_text()
                num = content[1].get_text()
                if num == "":
                    num = 0
                data['{}'.format(name)] = num
            except AttributeError as e:
                continue

        return JsonResponse(data, json_dumps_params={'ensure_ascii': False})

演示地址https://www.guanacossj.com/china-wuhan

后端数据格式

{"湖北": "1423", "广东": "151", "浙江": "128", "河南": "128", "重庆": "110", "湖南": "100", "山东": "75", "北京": "72", "安徽": "70", "四川": "69", "福建": "56", "上海": "53", "江西": "48", "江苏": "47", "广西": "46", "陕西": "35", "海南": "33", "辽宁": "27", "云南": "26", "天津": "22", "黑龙江": "21", "河北": "18", "甘肃": "14", "山西": "13", "内蒙古": "11", "香港": "8", "贵州": "7", "宁夏": "7", "吉林": "6", "澳门": "6", "台湾": "5", "新疆": "5", "青海": "4"}

由于Echarts中要求的数据长这样

var datavirus=[
            {name:"南海诸岛",value: 0},
            {name: '北京', value: 14},
            {name: '天津', value: 4},
            {name: '上海', value: 16},
            {name: '重庆', value: 9},
            ...
]

所以前端要处理一下

for(var i in dataStage) {
    var statisticsObj = {name:'',value:''};  //因为ECharts里边需要的的数据格式是这样的
    statisticsObj.name = i;
    statisticsObj.value = dataStage[i];
    statisticsData.push(statisticsObj);      //把拿到的异步数据push进我自己建的数组里
}

引入sweetalert2和echarts

<!-- include echarts -->
<script src="/static/china/dist/echarts.js"></script>
<script src="/static/china/map/js/china.js"></script>
<script src="/static/JiaBlog/js/jquery.js"></script>
<!-- include jQuery -->
<script src="/static/JiaBlog/js/jquery.main.js"></script>
<!-- include sweetalert2 -->
<script src="/static/sweetalert2/js/sweetalert2.js"></script>
<script src="/static/sweetalert2/js/sweetalert2.min.js"></script>
<script src="/static/sweetalert2/js/sweetalert2.all.js"></script>
<script src="/static/sweetalert2/js/sweetalert2.all.min.js"></script>

完整的ajax请求如下

var statisticsData = [];               //这是我自己建的空数组,为了把异步拿到的数据push进去
$.ajax({
    type : "get",
    async : true,                      //异步请求(同步请求将会锁住浏览器,用户其他操作必须等待请求完成才可以执行)
    url : "/china-wuhan/virusdata",    //请求发送到相应的Django
    dataType : "json",
    success : function(data){
        if (data) {
            var dataStage = data;
            for(var i in dataStage) {
                var statisticsObj = {name:'',value:''};   //因为ECharts里边需要的的数据格式是这样的
                statisticsObj.name = i;
                statisticsObj.value = dataStage[i];
                statisticsData.push(statisticsObj);   //把拿到的异步数据push进我自己建的数组里
            }

            myChart.hideLoading();
            myChart.setOption({
                series: [{
                   name: '确诊人数',
                    type: 'map',
                    geoIndex: 0,
                    data: statisticsData
                    }]
            });
            myChart.on('click', function (params) {
                // Sweetalert2
                Swal.fire(
                    params.name+"确诊人数"+params.data['value']+"人",
                    '',
                    )
            });
       }
       else {
           alert("图表请求数据失败!");
       }
    }
});

整个过程分两步,第一步加载data为空的初始的图表

var myChart = echarts.init(document.getElementById('main'));
myChart.setOption({
    backgroundColor: '#404a59',
    title:  {
        text: '武汉疫情',
        x: 'center',
        textStyle: {
            fontSize:28,
            color: '#fff'
        },
    },
    tooltip: {
        formatter:function(params,ticket, callback){
            return params.seriesName+'<br />'+params.name+':'+params.value
        }//数据格式化
    },
    visualMap: {
        min: 0,
        max: 50,
        align: 'auto',
        {#type: 'piecewise',    //是否连续#}
        left: 'left',
        top: 'bottom',
        text: ['高','低'],    //取值范围的文字
        inRange: {
        color:         ['#fdfff8','#f0a23f','#DD7931','#dd5340','#dd292f','#DD3E1B','#DD2020','#742B33',],
        },
        show:false//图注
    },
    geo: {
        map: 'china',
        roam: false,//不开启缩放和平移
        zoom:1.23,//视角缩放比例
        label: {
            normal: {
                show: true,
                fontSize:'10',
                 color: 'rgba(0,0,0,0.7)'
            }},
        itemStyle: {
            normal:{
                borderColor: 'rgba(0, 0, 0, 0.2)'
            },
            emphasis:{
                areaColor: '#53adf3',//鼠标选择区域颜色
                shadowOffsetX: 0,
                shadowOffsetY: 0,
                shadowBlur: 20,
                borderWidth: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
        }
    },
    series : [
        {
            name: '确诊人数',
            type: 'map',
            geoIndex: 0,
            data: []
        }
    ]
});

第二步,通过ajax传入data数据

var statisticsData = [];               //这是我自己建的空数组,为了把异步拿到的数据push进去
$.ajax({
    type : "get",
    async : true,                      //异步请求(同步请求将会锁住浏览器,用户其他操作必须等待请求完成才可以执行)
    url : "/china-wuhan/virusdata",    //请求发送到相应的Django
    dataType : "json",
    success : function(data){
        if (data) {
            var dataStage = data;
            for(var i in dataStage) {
                var statisticsObj = {name:'',value:''};   //因为ECharts里边需要的的数据格式是这样的
                statisticsObj.name = i;
                statisticsObj.value = dataStage[i];
                statisticsData.push(statisticsObj);   //把拿到的异步数据push进我自己建的数组里
            }

            myChart.hideLoading();
            myChart.setOption({
                series: [{
                   name: '确诊人数',
                    type: 'map',
                    geoIndex: 0,
                    data: statisticsData
                    }]
            });
            myChart.on('click', function (params) {
                // Sweetalert2
                Swal.fire(
                    params.name+"确诊人数"+params.data['value']+"人",
                    '',
                    )
            });
       }
       else {
           alert("图表请求数据失败!");
       }
    }
});
    ArithmeticJia         0         55         Django         1    

David Ramon

ArithmeticJia

www.guanacossj.com

Life is Short,You need Python

Related Posts

You may like these post too

image description

用Django写一个自己的博客网站

##写在最前面: 想用Django写网站很久了,本地也建立过很多demo,对于整个框架的入门算是熟练了。用pycharm可 以很方便的新建一个Django工程。专业版的Pycharm是自带Django的,目前Diango的最新版本应该是2.1。 IDE:Pycharm python版本

image description

Django和Flask的区别

##写在最前面: python web开发有很多常用的框架,主要包括Django,Flask,Tornado,Diesel,Cubes,Pulsar,Falcon,webpy,大家最熟知的还是Django和Flask,今天就来简单介绍一下Django和Flask的区别,本博客就是使用Django开

Comments on this post

0 comments

Leave a comment

it’s easy to post a comment

image description
image description
image description
image description
image description
image description
image description
image description
image description

Copyright © 2019.Company name All rights reserved.苏ICP备19007197号