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

中国地图省市下钻描点

程序员文章站 2024-01-19 12:32:52
...

接到一个需求,要从中国地图点击后下钻到省,在省地图上显示散点。遇到两个有困难的地方,一个是下钻后再省地图描点,再就是后台传经纬度直接画点。

我找了一些资料只找到下钻的,没有下钻后再画散点的只能自己玩了。其实也不难就是先找到点击事件再找到点击事件中根据对应省json画地图的地方就可以了,代码如下


var zhongguo = 'assets/json/china.json';
var hainan = "assets/json/hainan.json";
var xizang = "assets/json/xizang.json";
var zhejiang = "assets/json/zhejiang.json";
var yunnan = "assets/json/yunnan.json";
var * = "assets/json/*.json";
var tianjin = "assets/json/tianjin.json";
var sichuan = "assets/json/sichuan.json";
var shanxi = "assets/json/shanxi.json";
var shangxi = "assets/json/shanxi1.json";
var shanghai = "assets/json/shanghai.json";
var shangdong = "assets/json/shandong.json";
var qinghai = "assets/json/qinghai.json";
var ningxia = "assets/json/ningxia.json";
var neimenggu = "assets/json/neimenggu.json";
var liaoning = "assets/json/liaoning.json";
var jilin = "assets/json/jilin.json";
var jiangxi = "assets/json/jiangxi.json";
var jiangsu = "assets/json/jiangsu.json";
var hunan = "assets/json/hunan.json";
var hubei = "assets/json/hubei.json";
var henan = "assets/json/henan.json";
var heilongjiang = "assets/json/heilongjiang.json";
var hebei = "assets/json/hebei.json";
var guizhou = "assets/json/guizhou.json";
var guangxi = "assets/json/guangxi.json";
var guangdong = "assets/json/guangdong.json";
var gansu = "assets/json/gansu.json";
var chongqing = "assets/json/chongqing.json";
var aomen = "assets/json/aomen.json";
var anhui = "assets/json/anhui.json";
var beijing = "assets/json/beijing.json";
var fujian = "assets/json/fujian.json";
var xianggang = "assets/json/xianggang.json";

echarts.extendsMap = function(id, opt) {
    // 实例
    var chart = this.init(document.getElementById(id));
    var geoCoordMap = {
    	    '北碚': [106.50,29.81]
    }
    var geoCoordMap = {
    		   '北京':[116.4,39.9],
    		    '张家口':[114.9,40.8],
    		    '上海':[121.5,31.2],
    		    '佛山':[113.1,23],
    		    '惠州':[114.4,23.1],
    		    '嘉兴':[120.8,30.7],
    		    '黔西南州':[104.9,25.1],
    		    '湖州':[120.1,30.9],
    		    '苏州':[120.6,31.3],
    		    '无锡':[120.3,31.5],
    		    '南京':[118.8,32.1],
    		    '太原':[112.5,37.9],
    		    '晋中':[112.7,37.7],
    		    '西安':[108.9,34.3],
    		    '长沙':[112.9,28.2],
    		    '株洲':[113.2,27.8],
    		    '武汉':[114.3,30.6],
    		    '荆州':[112.2,30.3],
    		    '黄石':[115,30.2],
    		    '合肥':[117.2,31.8],
    		    '九华山':[117.8,30.5],
    		    '泉州':[118.7,24.9],
    		    '福州':[119.3,26.1],
    		    '南昌':[115.9,28.7],
    		    '九江':[116,29.7],
    		    '仙桃':[113.4,30.4],
    		    '天门':[113.2,30.7],
    		    '东戴河':[119.9,40],
    		    '广州':[113.3,23.1],

    		    '大庆':[125.03,46.58],
    		    '*': [86.61 , 40.79],
    		    '*':[89.13 , 30.66],
    		    '黑龙江':[128.34 , 47.05],
    		    '吉林':[126.32 , 43.38],
    		    '辽宁':[123.42 , 41.29],
    		    '内蒙古':[112.17 , 42.81],
    		    '北京':[116.40 , 40.40 ],
    		    '宁夏':[106.27 , 36.76],
    		    '山西':[111.95,37.65],
    		    '河北':[115.21 , 38.44],
    		    '天津':[117.04 , 39.52],
    		    '青海':[97.07 , 35.62],
    		    '甘肃':[103.82 , 36.05],
    		    '山东':[118.01 , 36.37],
    		    '陕西':[108.94 , 34.46],
    		    '河南':[113.46 , 34.25],
    		    '安徽':[117.28 , 31.86],
    		    '江苏':[120.26 , 32.54],
    		    '上海':[121.46 , 31.28],
    		    '四川':[103.36 , 30.65],
    		    '湖北':[112.29 , 30.98],
    		    '浙江':[120.15 , 29.28],
    		    '重庆':[107.51 , 29.63],
    		    '湖南':[112.08 , 27.79],
    		    '江西':[115.89 , 27.97],
    		    '贵州':[106.91 , 26.67],
    		    '福建':[118.31 , 26.07],
    		    '云南':[101.71 , 24.84],
    		    '*':[121.01 , 23.54],
    		    '广西':[108.67 , 23.68],
    		    '广东':[113.98 , 22.82],
    		    '海南':[110.03 , 19.33]
    		};
    
    var data = [
                { name: '*', value: 57 },
                { name: '张家口', value: 47 },
                { name: '上海', value: 3 },
                { name: '上海', value: 3 },
                { name: '佛山', value: 22 },
                { name: '嘉兴', value: 6 },
                { name: '黔西南州', value: 17 },
                { name: '湖州', value: 34 },
                { name: '苏州', value: 33 },
                { name: '无锡',  value: 5},
                { name: '南京', value: 5 },
                { name: '太原', value: 55 },
                { name: '晋中', value: 23 },
                { name: '西安', value: 4 },
                { name: '长沙', value: 49 },
                { name: '株洲', value: 17 },
                { name: '武汉', value: 57 },
                { name: '荆州', value: 10 },
                { name: '黄石', value: 21 },
                { name: '合肥', value: 54 },
                { name: '九华山', value: 5 },
                { name: '泉州', value: 45 },
                { name: '福州', value: 9 },
                { name: '九江', value: 3 },
                { name: '仙桃', value: 63 },
                { name: '天门', value: 10 },
                { name: '东戴河', value: 28 },
                { name: '广州', value: 29 }

           ];
    
    var provinceData = [              
               { name: '海南', value: '海南' },
               { name: '广东', value: 47 },
               { name: '广西', value: 3 },
               { name: '*', value: 3 },
               { name: '云南', value: 22 },
               { name: '福建', value: 6 },
               { name: '贵州', value: 17 },
               { name: '江西', value: 34 },
               { name: '湖南', value: 33 },
               { name: '重庆',  value: 5},
               { name: '浙江', value: 5 },
               { name: '湖北', value: 55 },
               { name: '四川', value: 23 },
               { name: '上海', value: 4 },
               { name: '江苏', value: 49 },
               { name: '安徽', value: 17 },
               { name: '河南', value: 57 },
               { name: '陕西', value: 10 },
               { name: '山东', value: 21 },
               { name: '甘肃', value: 54 },
               { name: '青海', value: 5 },
               { name: '河北', value: 45 },
               { name: '山西', value: 9 },
               { name: '宁夏', value: 3 },
               { name: '内蒙古', value: 63 },
               { name: '辽宁', value: 10 },
               { name: '吉林', value: 28 },
               { name: '黑龙江', value: 29 },
               { name: '*', value: 29 },
               { name: '*', value: 29 }
           ];
    var curGeoJson = {};
    let convertData = function (data) {
        let res = [];
        for (let i = 0; i < data.length; i++) {
            let geoCoord = geoCoordMap[data[i].name];
            if (geoCoord) {
                res.push({
                    name: data[i].name,
                    value: geoCoord.concat(data[i].value)
                });
            }
        }
        return res;
    };
    var cityMap = {
        '中国': zhongguo,
        '上海': shanghai,
        '河北': hebei,
        '山西': shangxi,
        '内蒙古': neimenggu,
        '辽宁': liaoning,
        '吉林': jilin,
        '黑龙江': heilongjiang,
        '江苏': jiangsu,
        '浙江': zhejiang,
        '安徽': anhui,
        '福建': fujian,
        '江西': jiangxi,
        '山东': shangdong,
        '河南': henan,
        '湖北': hubei,
        '湖南': hunan,
        '广东': guangdong,
        '广西': guangxi,
        '海南': hainan,
        '四川': sichuan,
        '贵州': guizhou,
        '云南': yunnan,
        '*': xizang,
        '陕西': shanxi,
        '甘肃': gansu,
        '青海': qinghai,
        '宁夏': ningxia,
        '*': *,
        '北京': beijing,
        '天津': tianjin,
        '重庆': chongqing,
        '香港': xianggang,
        '澳门': aomen
    };
    var levelColorMap = {
        '1': 'rgba(241, 109, 115, .8)',
        '2': 'rgba(255, 235, 59, .7)',
        '3': 'rgba(147, 235, 248, 1)'
    };

    var defaultOpt = {
        mapName: 'china', // 地图展示
        goDown: false, // 是否下钻
       // bgColor: '#404a59', // 画布背景色
        activeArea: [], // 区域高亮,同echarts配置项
        data: [],
        // 下钻回调(点击的地图名、实例对象option、实例对象)
        callback: function(name, option, instance) {}
    };
    if (opt) opt = this.util.extend(defaultOpt, opt);

    // 层级索引
    var name = [opt.mapName];
    var idx = 0;
    var pos = {
        leftPlus: 115,
        leftCur: 150,
        left: 198,
        top: 50
    };

    var line = [
        [0, 0],
        [8, 11],
        [0, 22]
    ];
    // style
    var style = {
        font: '18px "Microsoft YaHei", sans-serif',
        textColor: '#eee',
        lineColor: 'rgba(147, 235, 248, .8)'
    };

    var handleEvents = {
        /**
         * i 实例对象
         * o option
         * n 地图名
         **/
        resetOption: function(i, o, n) {
        	debugger
            var breadcrumb = this.createBreadcrumb(n);
            var j = name.indexOf(n);
            var l = o.graphic.length;
            if (j < 0) {
                o.graphic.push(breadcrumb);
                o.graphic[0].children[0].shape.x2 = 145;
                o.graphic[0].children[1].shape.x2 = 145;
                if (o.graphic.length > 2) {
                    var cityData = [];
                    var cityJson;
                    for (var x = 0; x < opt.data.length; x++) {
                        if (n === opt.data[x].city) {
                            $([opt.data[x]]).each(function(index, data) {
                                cityJson = {
                                    city: data.city,
                                    name: data.name,
                                    value: data.value,
                                    crew: data.crew,
                                    company: data.company,
                                    position: data.position,
                                    region: data.region
                                };
                                cityData.push(cityJson)
                            })
                        }
                    }

                    if (cityData != null) {
                    	
                        o.series[0].data = convertData(data.sort(function (a, b) {
                            return b.value - a.value;
                        }).slice(0, 50));
                    } else {
                        o.series[0].data = convertData(provinceData.sort(function (a, b) {
                            return b.value - a.value;
                        }).slice(0, 50));
                    }


                }
                name.push(n);
                idx++;
            } else {
                o.graphic.splice(j + 2, l);
                if (o.graphic.length <= 2) {
                    o.graphic[0].children[0].shape.x2 = 60;
                    o.graphic[0].children[1].shape.x2 = 60;
                    console.log(handleEvents.initSeriesData(provinceData));
                    
                    o.series[0].data = handleEvents.initSeriesData(provinceData);
                };
                name.splice(j + 1, l);
                idx = j;
                pos.leftCur -= pos.leftPlus * (l - j - 1);
            };

            o.geo.map = n;
            o.geo.zoom = 0.4;
            i.clear();
            i.setOption(o);
            this.zoomAnimation();
            opt.callback(n, o, i);
        },

        /**
         * name 地图名
         **/
        createBreadcrumb: function(name) {
            var cityToPinyin = {
                '中国': 'zhongguo',
                '上海': 'shanghai',
                '河北': 'hebei',
                '山西': 'shangxi',
                '内蒙古': 'neimenggu',
                '辽宁': 'liaoning',
                '吉林': 'jilin',
                '黑龙江': 'heilongjiang',
                '江苏': 'jiangsu',
                '浙江': 'zhejiang',
                '安徽': 'anhui',
                '福建': 'fujian',
                '江西': 'jiangxi',
                '山东': 'shangdong',
                '河南': 'henan',
                '湖北': 'hubei',
                '湖南': 'hunan',
                '广东': 'guangdong',
                '广西': 'guangxi',
                '海南': 'hainan',
                '四川': 'sichuan',
                '贵州': 'guizhou',
                '云南': 'yunnan',
                '*': 'xizang',
                '陕西': 'shanxi',
                '甘肃': 'gansu',
                '青海': 'qinghai',
                '宁夏': 'ningxia',
                '*': '*',
                '北京': 'beijing',
                '天津': 'tianjin',
                '重庆': 'chongqing',
                '香港': 'xianggang',
                '澳门': 'aomen'
            };
            var breadcrumb = {
                type: 'group',
                id: name,
                left: pos.leftCur + pos.leftPlus,
                top: pos.top + 3,
                children: [{
                    type: 'polyline',
                    left: -90,
                    top: -5,
                    shape: {
                        points: line
                    },
                    style: {
                        stroke: '#fff',
                        key: name
                        // lineWidth: 2,
                    },
                    onclick: function() {
                        var name = this.style.key;
                        handleEvents.resetOption(chart, option, name);
                    }
                }, {
                    type: 'text',
                    left: -68,
                    top: 'middle',
                    style: {
                        text: name,
                        textAlign: 'center',
                        fill: style.textColor,
                        font: style.font
                    },
                    onclick: function() {
                        var name = this.style.text;
                        handleEvents.resetOption(chart, option, name);
                    }
                }, {
                    type: 'text',
                    left: -68,
                    top: 10,
                    style: {

                        name: name,
                        text: cityToPinyin[name] ? cityToPinyin[name].toUpperCase() : '',
                        textAlign: 'center',
                        fill: style.textColor,
                        font: '12px "Microsoft YaHei", sans-serif',
                    },
                    onclick: function() {
                        // console.log(this.style);
                        var name = this.style.name;
                        handleEvents.resetOption(chart, option, name);
                    }
                }]
            }

            pos.leftCur += pos.leftPlus;

            return breadcrumb;
        },

        // 设置effectscatter
        initSeriesData: function(data) {
            var temp = [];
            for (var i = 0; i < data.length; i++) {
                var geoCoord = geoCoordMap[data[i].name];
                if (geoCoord) {
                    temp.push({
                        name: data[i].name,
                        value: geoCoord.concat(data[i].value),
                        crew: data[i].crew,
                        company: data[i].company,
                        position: data[i].position,
                        region: data[i].region
                    });
                }
            };
            return temp;
        },
        zoomAnimation: function() {
            var count = null;
            var zoom = function(per) {
                if (!count) count = per;
                count = count + per;
                // console.log(per,count);
                chart.setOption({
                    geo: {
                        zoom: count
                    }
                });
                if (count < 1) window.requestAnimationFrame(function() {
                    zoom(0.2);
                });
            };
            window.requestAnimationFrame(function() {
                zoom(0.2);
            });
        }
    };

    var option = {
        backgroundColor: opt.bgColor,
        tooltip: {
            show: true,
            trigger: 'item',
            alwaysShowContent: false,
            backgroundColor: 'rgba(50,50,50,0.7)',
            hideDelay: 100,
            triggerOn: 'mousemove',
            enterable: true,
            position: ['60%', '70%'],
            formatter: function(params, ticket, callback) {
                return '简称:' + params.data.name + '<br/>' + '机组:' + params.data.crew + '万千瓦' + '<br/>' + '公司名称:' + params.data.company + '<br/>' + '所属大区:' + params.data.region + '<br/>' + '所在位置:' + params.data.position
            }
        },
        graphic: [{
                type: 'group',
                left: pos.left,
                top: pos.top - 4,
                children: [{
                    type: 'line',
                    left: 0,
                    top: -20,
                    shape: {
                        x1: 0,
                        y1: 0,
                        x2: 60,
                        y2: 0
                    },
                    style: {
                        stroke: style.lineColor,
                    }
                }, {
                    type: 'line',
                    left: 0,
                    top: 20,
                    shape: {
                        x1: 0,
                        y1: 0,
                        x2: 60,
                        y2: 0
                    },
                    style: {
                        stroke: style.lineColor,
                    }
                }]
            },
            {
                id: name[idx],
                type: 'group',
                left: pos.left + 2,
                top: pos.top,
                children: [{
                    type: 'polyline',
                    left: 90,
                    top: -12,
                    shape: {
                        points: line
                    },
                    style: {
                        stroke: 'transparent',
                        key: name[0]
                    },
                    onclick: function() {
                        var name = this.style.key;
                        handleEvents.resetOption(chart, option, name);
                    }
                }, {
                    type: 'text',
                    left: 0,
                    top: 'middle',
                    style: {
                        text: '中国',
                        textAlign: 'center',
                        fill: style.textColor,
                        font: style.font
                    },
                    onclick: function() {
                    	console.log(option);
                        handleEvents.resetOption(chart, option, '中国');
                    }
                }, {
                    type: 'text',
                    left: 0,
                    top: 10,
                    style: {
                        text: 'China',
                        textAlign: 'center',
                        fill: style.textColor,
                        font: '12px "Microsoft YaHei", sans-serif',
                    },
                    onclick: function() {
                        handleEvents.resetOption(chart, option, '中国');
                    }
                }]
            }
        ],
        geo: {
            map: opt.mapName,
            roam: true,
            zoom: 1,
            label: {
            	fontSize:20,
                normal: {
                    show: false,
                    textStyle: {
                        color: 'rgba(0, 0, 205, 0)'
                    }
                },
                emphasis: {
                	label:{
                		show:false
                	},
                    textStyle: {
                        color: 'rgba(0, 0, 205, 0)'
                    }
                }
            },
            itemStyle: {
                normal: {
                    borderColor: 'rgba(0, 0, 205, 1)',
                    borderWidth: 1,
                    areaColor: '#F5FFFA',
                    shadowColor: 'rgba(128, 217, 248, 1)',
                    // shadowColor: 'rgba(255, 255, 255, 1)',
                    shadowOffsetX: -2,
                    shadowOffsetY: 2,
                    shadowBlur: 10
                },
                emphasis: {
                	label:{
                		show:false,
                		fontSize:0
                	},
                    areaColor: '#389BB7',
                    borderWidth: 0
                }
            },
            regions: opt.activeArea.map(function(item) {
            	alert(item.name);
                if (typeof item !== 'string') {
                    return {
                        name: item.name,
                        itemStyle: {
                            normal: {
                                areaColor: item.areaColor || '#389BB7'
                            }
                        },
                        label: {
                            normal: {
                                show: item.showLabel,
                                textStyle: {
                                    color: '#fff'
                                }
                            }
                        }
                    }
                } else {
                    return {
                        name: item,
                        itemStyle: {
                            normal: {
                                borderColor: '#FFFFFF',
                                areaColor: '#FFFFFF'
                            }
                        }
                    }
                }
            })
        },
        series: [{
            type: 'scatter',
            symbolSize:1,
            coordinateSystem: 'geo',
            showEffectOn: 'render',
            rippleEffect: {
                period: 15,
                scale:35,
                brushType: 'fill'
            },
            label:{
            	show:true,
            	formatter:'{b}'
            },
            hoverAnimation: true,
            itemStyle: {
                normal: {
                    color: '#000000',
                    shadowBlur: 10,
                    shadowColor: '#333'
                }
            },
            data: handleEvents.initSeriesData(provinceData)
        }]
    };

    chart.setOption(option);
    // 添加事件
    chart.on('click', function(params) {
        var _self = this;
        if (opt.goDown && params.name !== name[idx]) {
            if (cityMap[params.name]) {
                var url = cityMap[params.name];
                $.get(url, function(response) {
                    //console.log(response);
                    curGeoJson = response;
                    echarts.registerMap(params.name, response);
                    option.geo.label.normal.show=false;
                    option.series[0].data = convertData(data.sort(function (a, b) {
                        return b.value - a.value;
                    }).slice(0, 50));
                    handleEvents.resetOption(_self, option, params.name);
                });
            }
        }
    });



    return chart;
};

$.getJSON(zhongguo, function(geoJson) {
    echarts.registerMap('中国', geoJson);
    debugger
    var myChart = echarts.extendsMap('china_map', {
       // bgColor: '#154e90', // 画布背景色
        mapName: '中国', // 地图名
        goDown: true, // 是否下钻
        // 下钻回调
        callback: function(name, option, instance) {
            //console.log(name, option, instance);
        },

    });
})

代码主体是找社区里大佬分享的,分析了下就是在点击事件里有个resetOption方法,然后这个option的series里的data改成自己要的散点坐标就ok啦。

然后就是后台传坐标

 $.ajax({
	    url:"../../../proxy/yl/gc/v1/getMemberUnit/getMemberUnitListByCityCode",    //请求的url地址
	    dataType:"json",  
	    contentType: 'application/json',
	    async:false,
	    data:JSON.stringify(obj3),    //参数值
	    type:"POST",   //请求方式		   
	    success:function(req){
	        //请求成功时处理
	        
	        for(var i = 0;i<req.data.length;i++){
	        	geoCoordMap[req.data[i].unitName]=req.data[i].coordinate;
	        	var json ={};
	        	json.name = req.data[i].unitName;
	        	json.value = req.data[i].unitAddr;
	        	json.addr = req.data[i].unitAddr;
	        	json.leader = req.data[i].leader;
	        	provinceData.push(json);
	        }	        
	    }

一开始没太高清楚这个画散点的机制,后来发现就是一个json里面根据省市的名字作为属性,值作为坐标来画的,搞清楚这点就只需要在后台稍作处理,把数据库的字符串处理成数组就可以了。