欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

OpenLayers在地图上显示统计图,饼图线状图柱状图,修复统计图跳动的问题

程序员文章站 2022-07-06 11:53:15
显示效果 地图放大缩小对统计图的大小无影响 以饼状图为例 1、添加地图,并渲染统计图所在的点位, 2、画点的方法 3、添加统计图 下面是原始的方法,可以显示统计图,但是初始位置不对,但是稍微拖动下地图,位置又跳到对的位置了,没找到问题,换成了后面的方法2 可能是因为对Overlay的element做 ......

 

环境介绍
openlayers ol.js v5.3.0
highcharts highcharts.js v7.0.1
jquery jquery-3.3.1.js v3.3.1

 

 

 

 

 

显示效果

OpenLayers在地图上显示统计图,饼图线状图柱状图,修复统计图跳动的问题

OpenLayers在地图上显示统计图,饼图线状图柱状图,修复统计图跳动的问题

OpenLayers在地图上显示统计图,饼图线状图柱状图,修复统计图跳动的问题

地图放大缩小对统计图的大小无影响

以饼状图为例

1、添加地图,并渲染统计图所在的点位,

vector是渲染feature需要用的图层,一定要保证在所有图层的最前方,否则渲染的feature会被遮盖,(地图量算时由于这个问题搞了一上午)
sourcemeasure = new ol.source.vector({ wrapx: false });

    vector = new ol.layer.vector({
        source: sourcemeasure,
        style: new ol.style.style({
            fill: new ol.style.fill({
                color: 'rgba(255, 255, 0, 0.2)'
            }),
            stroke: new ol.style.stroke({
                color: '#ffcc33',
                width: 2
            }),
            image: new ol.style.circle({
                radius: 7,
                fill: new ol.style.fill({
                    color: '#ffaa33'
                })
            })
        })
    });

    map = new ol.map({
        controls: ol.control.defaults({
            attribution: false
        }),
        target: 'map',
        layers: [
            new ol.layer.tile({
                source: new ol.source.osm()
            }),
            vector
        ],
        view: new ol.view({
            projection: 'epsg:3857',
            center: ol.proj.transform([121, 37], 'epsg:4326', 'epsg:3857'),
            //center: [121, 37],
            zoom: 6
        })
    });

    drawpoint();

2、画点的方法

function drawpoint() {
    for (var i = 0; i < datapie.length; i++) {
        var d = datapie[i];
        var pt = ol.proj.transform([d.x, d.y], 'epsg:4326', 'epsg:3857');

        var point = new ol.geom.point(pt);

        var feature = new ol.feature(point);

        sourcemeasure.addfeature(feature);
    }
}

3、添加统计图

下面是原始的方法,可以显示统计图,但是初始位置不对,但是稍微拖动下地图,位置又跳到对的位置了,没找到问题,换成了后面的方法2

//方法1
//$("#addpiechart").on("click", function () { // clearchartoverlay(); // for (var i = 0; i < datapie.length; i++) { // var d = datapie[i]; // var pt = ol.proj.transform([d.x, d.y], 'epsg:4326', 'epsg:3857'); // var domid = "chart" + guid(); // $("#chart").append("<div id='" + domid + "'></div>"); // var chart = new ol.overlay({ // id: domid, // position: pt, // positioning: "bottom-center", // element: document.getelementbyid(domid), // offset: [0, 18], // stopevent: false //overlay也支持滚珠放大缩小 // }); // map.addoverlay(chart); // addpiechart(domid, d, 100); // overlayid.push(domid); // } //});

可能是因为对overlay的element做了设置解决的这个问题,比较玄学

//方法2 
$("#addpiechart").on("click", function () { clearchartoverlay(); for (var i = 0; i < datapie.length; i++) { var d = datapie[i]; var pt = ol.proj.transform([d.x, d.y], 'epsg:4326', 'epsg:3857'); var domid = "chart" + guid(); $("#chart").append("<div id='" + domid + "'></div>"); addpiechart(domid, d, 100); var chart = new ol.overlay({ id: domid, element: document.getelementbyid(domid), positioning: "bottom-center", //统计图和渲染点位的位置关系 offset: [0, 18],//如果统计图相对于点位又偏移,可以通过此属性将统计图移回来 stopevent: false //overlay也支持滚珠放大缩小 }); map.addoverlay(chart); var element = chart.getelement(); chart.setposition(pt); //使用下面的方法显示overlay,可避免初始位置不对,拖动一下地图跳动的问题 $(element).popover({ placement: 'top', animation: false }); $(element).popover('show'); overlayid.push(domid); } });

  移除所有用来显示统计图的overlay,和饼图的方法,highcharts里很多,想要别的风格可以去看highcharts的api

/**
 * 移除统计图所使用的overlay
 * */
function clearchartoverlay() {
    for (var i = 0; i < overlayid.length; i++) {
        map.removeoverlay(map.getoverlaybyid(overlayid[i]));
    }
}

function addpiechart(domid, data, size) {
    $('#' + domid).highcharts({
        chart: {
            backgroundcolor: 'rgba(255, 255, 255, 0)',
            plotbordercolor: null,
            plotbackgroundcolor: null,
            plotbackgroundimage: null,
            plotborderwidth: null,
            plotshadow: false,
            width: size,
            height: size
        },
        tooltip: {
            pointformat: '<b>{point.percentage:.1f}%</b>'
        },
        credits: {
            enabled: false
        },
        title: {
            text: ''
        },
        plotoptions: {
            pie: {
                datalabels: {
                    enabled: false
                }
            }
        },
        series: [{
            type: 'pie',
            name: data.name,
            data: data.data
        }]
    });
}

  4、差不多就这么多,线状图和柱状图都类似,下面是完成代码

html

@{
    viewbag.title = "statisticalchart";
    layout = "~/views/shared/_layout.cshtml";
}

@styles.render("~/content/openlayers")

<div id="map" class="map">

</div>
<div class="tool">
    <button id="addpiechart">添加饼图</button>
    <button id="addlinechart">添加线状图</button>
    <button id="addcolumnchart">添加柱状图</button>
</div>
<div style="display: none;" id="chart">
</div>

@scripts.render("~/bundles/openlayers")
<script src="~/scripts/openlayers/mapstatisticalchart.js"></script>
<script src="~/scripts/highcharts/highcharts.js"></script>
<script type="text/javascript">

    $(document).ready(function () {
        init();
    });

</script>

  js

/*
 *地图上显示统计图
 */

//地图渲染的两个对象
var vector;
var sourcemeasure;

//x,y表示渲染的位置,如果是点图层好说,如果是面或者线,需要获取中心点
var overlayid = [];
var datapie = [{
    name: "乌鲁木齐", x: 87.5758285931, y: 43.7822116460, data: [
        {
            name: '男',
            y: 40.0,
            color: "#5ab1ef"
        }, {
            name: '女',
            y: 60.0,
            color: "#d87a80"
        }
    ]
},
{
    name: "拉萨", x: 91.1629975040, y: 29.7104204643, data: [
        {
            name: '男',
            y: 45.0,
            color: "#5ab1ef"
        }, {
            name: '女',
            y: 55.0,
            color: "#d87a80"
        }
    ]
},
{
    name: "北京", x: 116.4575803581078, y: 40.04054437977018, data: [
        {
            name: '男',
            y: 35.0,
            color: "#5ab1ef"
        }, {
            name: '女',
            y: 65.0,
            color: "#d87a80"
        }
    ]
},
{
    name: "兰州", x: 103.584297498, y: 36.1190864503, data: [
        {
            name: '男',
            y: 44.0,
            color: "#5ab1ef"
        }, {
            name: '女',
            y: 56.0,
            color: "#d87a80"
        }
    ]
}];
var map;
function init() {
    sourcemeasure = new ol.source.vector({ wrapx: false });

    vector = new ol.layer.vector({
        source: sourcemeasure,
        style: new ol.style.style({
            fill: new ol.style.fill({
                color: 'rgba(255, 255, 0, 0.2)'
            }),
            stroke: new ol.style.stroke({
                color: '#ffcc33',
                width: 2
            }),
            image: new ol.style.circle({
                radius: 7,
                fill: new ol.style.fill({
                    color: '#ffaa33'
                })
            })
        })
    });

    map = new ol.map({
        controls: ol.control.defaults({
            attribution: false
        }),
        target: 'map',
        layers: [
            new ol.layer.tile({
                source: new ol.source.osm()
            }),
            vector
        ],
        view: new ol.view({
            projection: 'epsg:3857',
            center: ol.proj.transform([121, 37], 'epsg:4326', 'epsg:3857'),
            //center: [121, 37],
            zoom: 6
        })
    });

    drawpoint();

    $("#addpiechart").on("click", function () {
        clearchartoverlay();
        for (var i = 0; i < datapie.length; i++) {
            var d = datapie[i];
            var pt = ol.proj.transform([d.x, d.y], 'epsg:4326', 'epsg:3857');
            var domid = "chart" + guid();
            $("#chart").append("<div id='" + domid + "'></div>");

            addpiechart(domid, d, 100);

            var chart = new ol.overlay({
                id: domid,
                element: document.getelementbyid(domid),
                positioning: "bottom-center",
                offset: [0, 18],
                stopevent: false  //overlay也支持滚珠放大缩小
            });
            map.addoverlay(chart);
            
            var element = chart.getelement();
            chart.setposition(pt);
            //使用下面的方法显示overlay,可避免初始位置不对,拖动一下地图跳动的问题
            $(element).popover({
                placement: 'top',
                animation: false
            });
            $(element).popover('show');
            
            overlayid.push(domid);
        }
    });

    $("#addlinechart").on("click", function () {
        clearchartoverlay();
        for (var i = 0; i < dataline.length; i++) {
            var d = dataline[i];
            var pt = ol.proj.transform([d.x, d.y], 'epsg:4326', 'epsg:3857');
            var domid = "chart" + guid();
            //$("#chart").append("<div id='" + domid + "'></div>");
            //var chart = new ol.overlay({
            //    id: domid,
            //    position: pt,
            //    positioning: "bottom-center",
            //    element: document.getelementbyid(domid),
            //    stopevent: false  //overlay也支持滚珠放大缩小
            //});
            //map.addoverlay(chart);
            //addlinechart(domid, d.data, 200, 150);
            //overlayid.push(domid);

            $("#chart").append("<div id='" + domid + "'></div>");
            var chart = new ol.overlay({
                id: domid,
                positioning: "bottom-center",
                element: document.getelementbyid(domid),
                stopevent: false  //overlay也支持滚珠放大缩小
            });
            map.addoverlay(chart);
            addlinechart(domid, d.data, 200, 150);
            

            var element = chart.getelement();
            chart.setposition(pt);
            //使用下面的方法显示overlay,可避免初始位置不对,拖动一下地图跳动的问题
            $(element).popover({
                placement: 'top',
                animation: false
            });
            $(element).popover('show');

            overlayid.push(domid);
        }
    });

    $("#addcolumnchart").on("click", function () {
        clearchartoverlay();
        for (var i = 0; i < datacolumn.length; i++) {
            var d = datacolumn[i];
            var pt = ol.proj.transform([d.x, d.y], 'epsg:4326', 'epsg:3857');
            var domid = "chart" + guid();
            $("#chart").append("<div id='" + domid + "'></div>");
            var chart = new ol.overlay({
                id: domid,
                positioning: "bottom-center",
                element: document.getelementbyid(domid),
                offset: [0, 5],
                stopevent: false  //overlay也支持滚珠放大缩小
            });
            map.addoverlay(chart);
            addcolumnchart(domid, d.data, 80, 80);

            var element = chart.getelement();
            chart.setposition(pt);
            //使用下面的方法显示overlay,可避免初始位置不对,拖动一下地图跳动的问题
            $(element).popover({
                placement: 'top',
                animation: false
            });
            $(element).popover('show');
            
            overlayid.push(domid);
        }
    });
}
/**
 * 移除统计图所使用的overlay
 * */
function clearchartoverlay() {
    for (var i = 0; i < overlayid.length; i++) {
        map.removeoverlay(map.getoverlaybyid(overlayid[i]));
    }
}

function addpiechart(domid, data, size) {
    $('#' + domid).highcharts({
        chart: {
            backgroundcolor: 'rgba(255, 255, 255, 0)',
            plotbordercolor: null,
            plotbackgroundcolor: null,
            plotbackgroundimage: null,
            plotborderwidth: null,
            plotshadow: false,
            width: size,
            height: size
        },
        tooltip: {
            pointformat: '<b>{point.percentage:.1f}%</b>'
        },
        credits: {
            enabled: false
        },
        title: {
            text: ''
        },
        plotoptions: {
            pie: {
                datalabels: {
                    enabled: false
                }
            }
        },
        series: [{
            type: 'pie',
            name: data.name,
            data: data.data
        }]
    });
}

var dataline = [{
    name: "乌鲁木齐", x: 87.5758285931, y: 43.7822116460, data: [
        {
            name: '安装,实施人员',
            series: [
                { x: 2010, y: 1234 },
                { x: 2011, y: 1234 }
            ],
            color: "#5ab1ef"
        }, {
            name: '工人',
            series: [
                { x: 2010, y: 245 },
                { x: 2011, y: 3454 }
            ],
            color: "#d87a80"
        }
    ]
},
{
    name: "拉萨", x: 91.1629975040, y: 29.7104204643, data: [
        {
            name: '安装,实施人员',
            series: [
                { x: 2010, y: 1234 },
                { x: 2011, y: 124 },
                { x: 2012, y: 0 }
            ],
            color: "#5ab1ef"
        }, {
            name: '工人',
            series: [
                { x: 2010, y: 245 },
                { x: 2011, y: 0 },
                { x: 2012, y: 3454 }
            ],
            color: "#d87a80"
        }
    ]
}];

function addlinechart(domid, data, width, height) {

    var categoriesx = [];
    var seriesvalue = [];
    for (var i = 0; i < data.length; i++) {
        var value = [];
        for (var j = 0; j < data[i].series.length; j++) {
            categoriesx.push(data[i].series[j].x);
            value.push(data[i].series[j].y);
        }

        seriesvalue.push({ "name": data[i].name, "data": value });
    }

    $('#' + domid).highcharts({
        chart: {
            backgroundcolor: 'rgba(255, 255, 255, 0.8)',
            borderradius: 20,
            plotbordercolor: null,
            plotbackgroundcolor: null,
            plotbackgroundimage: null,
            plotborderwidth: null,
            plotshadow: false,
            width: width,
            height: height
        },
        credits: {
            enabled: false
        },
        title: {
            text: ''
        },
        yaxis: {
            visible: false,
            title: {
                text: ''
            }
        },
        xaxis: {
            categories: categoriesx,
            crosshair: true
        },
        legend: {
            enabled: false
        },
        plotoptions: {
            series: {
                label: {
                    connectorallowed: false
                }
            },
            line: {
                datalabels: {
                    enabled: true,
                    formatter: function () {
                        return '<b>' + this.point.y + '</b><br>';
                    }
                }
            }
        },
        series: seriesvalue,
        responsive: {
            rules: [{
                condition: {
                    maxwidth: 500
                },
                chartoptions: {
                    legend: {
                        layout: 'horizontal',
                        align: 'center',
                        verticalalign: 'bottom'
                    }
                }
            }]
        }
    });
}

var datacolumn = [{
    name: "乌鲁木齐", x: 87.5758285931, y: 43.7822116460, data: [
        {
            name: '安装,实施人员',
            series: [
                { x: 2011, y: 1234 }
            ],
            color: "#5ab1ef"
        }, {
            name: '工人',
            series: [
                { x: 2011, y: 3454 }
            ],
            color: "#d87a80"
        }
    ]
},
{
    name: "拉萨", x: 91.1629975040, y: 29.7104204643, data: [
        {
            name: '安装,实施人员',
            series: [
                { x: 2012, y: 123 }
            ],
            color: "#5ab1ef"
        }, {
            name: '工人',
            series: [
                { x: 2012, y: 3454 }
            ],
            color: "#d87a80"
        }
    ]
}, {
    name: "北京", x: 116.4575803581078, y: 40.04054437977018, data: [
        {
            name: '安装,实施人员',
            series: [
                { x: 2014, y: 252 }
            ],
            color: "#5ab1ef"
        }, {
            name: '工人',
            series: [
                { x: 2014, y: 324 }
            ],
            color: "#d87a80"
        }
    ]
},
{
    name: "兰州", x: 103.584297498, y: 36.1190864503, data: [
        {
            name: '安装,实施人员',
            series: [
                { x: 2013, y: 2341 }
            ],
            color: "#5ab1ef"
        }, {
            name: '工人',
            series: [
                { x: 2013, y: 2341 }
            ],
            color: "#d87a80"
        }
    ]
}];

function addcolumnchart(domid, data, width, height) {

    var categoriesx = [];
    var seriesvalue = [];
    for (var i = 0; i < data.length; i++) {
        var value = [];
        for (var j = 0; j < data[i].series.length; j++) {
            categoriesx.push(data[i].series[j].x);
            value.push(data[i].series[j].y);
        }

        seriesvalue.push({ "name": data[i].name, "data": value });
    }

    $('#' + domid).highcharts({
        chart: {
            backgroundcolor: 'rgba(255, 255, 255, 0)',
            borderradius: 20,
            plotbordercolor: null,
            plotbackgroundcolor: null,
            plotbackgroundimage: null,
            plotborderwidth: null,
            plotshadow: false,
            width: width,
            height: height,
            type: 'column'
        },
        credits: {
            enabled: false
        },
        title: {
            text: ''
        },
        yaxis: {
            visible: false,
            title: {
                text: ''
            }
        },
        xaxis: {
            visible: false,
            categories: categoriesx,
            crosshair: true
        },
        legend: {
            enabled: false
        },
        plotoptions: {
            series: {
                label: {
                    connectorallowed: false
                }
            },
            line: {
                datalabels: {
                    enabled: true,
                    formatter: function () {
                        return '<b>' + this.point.y + '</b><br>';
                    }
                }
            }
        },
        series: seriesvalue,
        responsive: {
            rules: [{
                condition: {
                    maxwidth: 500
                },
                chartoptions: {
                    legend: {
                        layout: 'horizontal',
                        align: 'center',
                        verticalalign: 'bottom'
                    }
                }
            }]
        }
    });
}

function drawpoint() {
    for (var i = 0; i < datapie.length; i++) {
        var d = datapie[i];
        var pt = ol.proj.transform([d.x, d.y], 'epsg:4326', 'epsg:3857');

        var point = new ol.geom.point(pt);

        var feature = new ol.feature(point);

        sourcemeasure.addfeature(feature);
    }
}

  引用的资料包括:https://blog.csdn.net/gisshixisheng/article/details/50926948,https://blog.csdn.net/henrystern/article/details/81149015