VUE 记一次高德地图和Echarts(中国地图)

栏目: 编程语言 · 发布时间: 5年前

内容简介:高德地图Echarts 中国地图
VUE 记一次高德地图和Echarts(中国地图)

准备工作

  • 高德地图申请key
  • 安装Echarts 中国地图

高德地图

  • 官方API:点我进入
  • 创建AMap.js
export default function MapLoader () {
    return new Promise((resolve, reject) => {
      if (window.AMap) {
        resolve(window.AMap)
      } else {
      // 动态创建script标签
        var script = document.createElement('script')
        script.type = 'text/javascript'
        script.async = true
        script.src = 'https://webapi.amap.com/maps?v=1.4.9&callback=initAMap&key=Key&plugin=AMap.DistrictSearch,AMap.Circle,AMap.LngLat,AMap.Polyline,AMap.LngLat,AMap.Text,AMap.Geocoder';
        // plugin后的是需要的插件
        script.onerror = reject
        document.head.appendChild(script)
      }
      window.initAMap = () => {
        resolve(window.AMap)
      }
    })
}
复制代码

Echarts 中国地图

  • 安装Echarts
npm install echarts -S
复制代码

开始使用

  • 创建组件 distribution.vue
  • 写入Echarts 需要的DOM
<div class="main_wrap" >
        <div ref="main" class="main_box"></div>
            <div class="Rankingtips">
                <p>分布指数</p>
                <div class="color_tip">
                    <span style="float: left">高</span>
                    <div></div>
                    <div></div>
                    <div></div>
                    <div></div>
                    <div></div>
                    <span style="margin-left: 5px">低</span>
                </div>
        </div>
    </div>
复制代码
  • 写入高德地图需要的DOM
<div class="main_wrap" v-show="activeState2">
        <div id="container" style="height: 100%"></div>
    </div>
复制代码
  • 引入高德地图、Echarts
import 'echarts/map/js/china'; //中国地图js
    import MapLoader from 'components/home/AMap'
复制代码
  • Echarts方法
generateEcharts() {
    var echarts = require('echarts');
    var myChart = echarts.init(this.$refs.main);  // 基于准备好的dom,初始化echarts实例
    this.$ajax.get(this.HOST + "/redesign/home/findEnterpriseistribution").then( (res) => {
        // 数据格式
        // [
        //   {name: "北京", value: 3, ranking: 1},
        //   {name: "河北", value: 2, ranking: 2},
        //   {name: "上海", value: 1, ranking: 3},
        //   {name: "广东", value: 1, ranking: 4}
        //   ...
        // ]
        this.homebution = res.data.resultObject;
        var data = [];
        for (let i = 0; i < res.data.resultObject.length; i++) {
            this.homebutionnum += res.data.resultObject[i].value;
            let classnum = ""
            // 排名显示样式
            if(res.data.resultObject[i].ranking == 1) { 
                classnum = "#1669e6"
            }else if(res.data.resultObject[i].ranking > 1 && res.data.resultObject[i].ranking <= 4) {
                classnum = "#31a4ed"
            }else if(res.data.resultObject[i].ranking > 4 && res.data.resultObject[i].ranking <= 10) {
                classnum = '#2cccfd'
            }else if(res.data.resultObject[i].ranking > 10 && res.data.resultObject[i].ranking <= 20) {
                classnum = '#7fe2fd'
            }else {
                classnum = '#d9f4fe'
            }
            data.push(
                {
                    name: res.data.resultObject[i].name,
                    itemStyle: {
                        normal: {
                            areaColor: classnum,
                            // borderWidth: 2
                        },
                        emphasis: {//高亮状态下的多边形和标签样式
                            borderWidth: 1,
                            // borderColor: '#d9f4fe',
                            areaColor: '#d9f4fe',
                            label: {
                                shadowColor: '#d9f4fe', //默认透明
                                shadowBlur: 10,
                                show: true,
                                textStyle: {
                                    fontSize: 12,
                                    color: '#3db77f'
                                }
                            }
                        }
                    },
                    label: {
                        normal: {
                            show: true,
                            textStyle: {
                                fontSize: 12,
                                color: '#0d6fb8'
                            }
                        },
                        emphasis: {
                            show: true,
                            color: '#3db77f'
                        }
                    },
                    value: res.data.resultObject[i].value ? res.data.resultObject[i].value: "",
                    ranking: res.data.resultObject[i].ranking ? res.data.resultObject[i].ranking: ""
                }
            )
        }
        // 准备提示数据
        var option = {
            tooltip: {
                formatter:  (params) => {
                    var info = "";
                        if(params.data) {
                            info = `<div style="width: 60px;height: 60px">
                                <p style="font-size:12px">${ params.name }</p>
                                <p style="font-size:12px">${ params.data.value }</p>
                                <p style="font-size:12px">排名:${ params.data.ranking }</p>
                            </div>`
                        }else {
                            info = `<div style="width: 60px;height: 60px">
                                <p style="font-size:12px">${ params.name }</p>
                            </div>`
                        }
                    return info;
                },
                backgroundColor: "rgba(0,0,0,.6)",//提示标签背景颜色
                textStyle: { color: "#fff" } //提示标签字体颜色
            },
            //配置属性
            series: [{  
                name: '数据',  
                type: 'map',  
                mapType: 'china',   
                roam: true,  
                label: {  
                    normal: {  
                        show: false  //省份名称  
                    },  
                    emphasis: { 
                        show: false  
                    }  
                },  
                data: data  //数据
            }],
        };
        //使用制定的配置项和数据显示图表
        myChart.setOption(option);
    })
}
复制代码
  • 高德地图方法
Scottmap() {
    let that = this;
    that.map = "";
    MapLoader().then(AMap => {
        console.log('地图加载成功')
        that.map = new AMap.Map('container', {
            center: [116.05438, 38.98065],
            // center: [116.397428, 39.90923],
            zoom: 5
        })
        // 由于项目是按雄安地区使用 API暂时还未把雄安划分 所以决定把安新县、雄县、容城县(三县合一就是雄安)绘制成高亮
        // 绘制高亮
        var district = new AMap.DistrictSearch({
            // 返回行政区边界坐标等具体信息
            extensions: 'all',
            // 设置查询行政区级别为 区 
            level: 'district'
        })
        var polygons=[];
        var polygons2=[];
        var polygons3=[];
        district.search('安新县', (status, result) => {
            if(polygons) {
                that.map.remove(polygons)//清除上次结果
            }
            polygons = [];
            let bounds = result.districtList[0].boundaries;
            if (bounds) {
                for (let i = 0; i < bounds.length; i++) {
                    //生成行政区划polygon
                    var polygon = new AMap.Polygon({
                        strokeWeight: 1,
                        path: bounds[i],
                        fillOpacity: 0.4,
                        fillColor: '#80d8ff',
                        strokeColor: '#0091ea'
                    });
                    polygons.push(polygon);
                }
            }
            that.map.add(polygons);
        });
        district.search('雄县', (status2, result2) => {
            if(polygons2) {
                that.map.remove(polygons2)//清除上次结果
            }
            polygons2 = [];
            let bounds = result2.districtList[0].boundaries;
            if (bounds) {
                for (let i = 0; i < bounds.length; i++) {
                    //生成行政区划polygon
                    var polygon = new AMap.Polygon({
                        strokeWeight: 1,
                        path: bounds[i],
                        fillOpacity: 0.4,
                        fillColor: '#80d8ff',
                        strokeColor: '#0091ea'
                    });
                    polygons2.push(polygon);
                }
            }
            that.map.add(polygons2)
        })
        district.search('容城县', (status2, result2) => {
            if(polygons3) {
                that.map.remove(polygons2)//清除上次结果
            }
            polygons3 = [];
            let bounds = result2.districtList[0].boundaries;
            if (bounds) {
                for (let i = 0; i < bounds.length; i++) {
                    //生成行政区划polygon
                    var polygon = new AMap.Polygon({
                        strokeWeight: 1,
                        path: bounds[i],
                        fillOpacity: 0.4,
                        fillColor: '#80d8ff',
                        strokeColor: '#0091ea'
                    });
                    polygons3.push(polygon);
                }
            }
            that.map.add(polygons3)
        })
        // 构造矢量圆形(圆)
        let circle = new AMap.Circle({
            center:  [116.05438, 38.98065], // 雄安的中心点
            radius: that.distance * 1000,  //半径
            strokeColor: "#ffffff",  //线颜色
            strokeOpacity: 1,  //线透明度
            strokeWeight: 3,  //线粗细度
            fillColor: "#276cd4",  //填充颜色
            fillOpacity: 0.2 //填充透明度
        });
        that.map.add(circle);
        that.map.setFitView(circle);
        let lnglat = new AMap.LngLat(116.05438, 38.98065) // lng, lat 替换成传入的坐标 
        let polylinePath = [
            new AMap.LngLat(116.05438, 38.98065),
            new AMap.LngLat(lnglat.offset(that.distance * 1000,0).lng,38.98065)
        ];
        // 创建线覆盖物
        let polyline = new AMap.Polyline({
            path: polylinePath,
            strokeColor: "#ffffff", //线颜色
            strokeOpacity: 1,       //线透明度
            strokeWeight: 2,        //线宽
            strokeStyle: "solid",   //线样式
            strokeDasharray: [10, 5] //补充线样式
        });
        that.map.add(polyline);
        // 绘制字
        let textPos = lnglat.offset(that.distance * 500,that.distance * 50);
        let text = new AMap.Text({
            text: `${ that.distance }公里`,
            position: textPos,
            map: this.map,
            style:{
                    'background': 'transparent',
                    'border': '0 none',
                    'color': '#276cd4',
                    'font-size':'14px'}
        })
        that.map.add(text);
        // 测试距离
        let Centralpoint = [116.05438, 38.98065];
        let targetpoint = this.region
        // debugger
        // 转经纬度
        let geocoder = new AMap.Geocoder({
            city: '全国', //城市设为北京,默认:“全国”
        });
        let markernum = 0
        for (let i = 0; i < targetpoint.length; i++) {
            geocoder.getLocation(targetpoint[i], (status, result) => {
                if (status === 'complete'&& result.geocodes.length) {
                    let dis = AMap.GeometryUtil.distance(Centralpoint,result.geocodes[0].location);
                    // 绘制点标记显示内容,HTML要素字符串
                    if(dis <= that.distance * 1000) {
                        markernum++;
                        let markerContent = '' +
                            '<div class="custom-content-marker" style="position: relative;">' +
                            '   <img src="//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png" style="width: 23px;height: 30px">' +
                            '<div style="width: 23px;position: absolute;left: 0px;top: 0;margin: auto;color: #ffffff;text-align: center">'+ markernum +'</div>'+
                            '</div>';
                        this.$ajax.get(this.HOST + "/redesign/home/findCompanyAll").then( (res) => {
                            this.matchingenterpriseList.push(res.data.resultObject[i])
                        })
                        let marker = new AMap.Marker({
                            content: markerContent,                                
                            position: result.geocodes[0].location,
                            offset: new AMap.Pixel(-13, -30),
                            extData:{
                                id: markernum
                            }
                        });
                        that.markers.push(marker);
                        marker.setMap(this.map);
                    }
                }
        })
        }
        that.matchingenterpriseState = true;
    }, e => {
        console.log('地图加载失败' ,e)
    })
},
复制代码
  • 左侧企业列表
// 企业鼠标经过
matchingenterprisemouseenter(item,index) {
    this.activemetchmouseenter = index;
    let targetMarker = {};
    for (let i = 0; i < this.markers.length; i++) {
        let id = this.markers[i].getExtData().id;
        if(id == index){
            targetMarker = this.markers[i];
            break;
        }
    }
    // 重新替换样式
    let markerContent = '' +
        '<div class="custom-content-marker" style="position: relative;">' +
        '   <img src="//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png" style="width: 25px;height: 34px">' +
        '<div style="position: absolute;left: 9px;top: 0;margin: auto;color: #ffffff">'+ index +'</div>'+
        '</div>';
    // targetMarker.setIcon('//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png');
    targetMarker.setContent(markerContent)
    let position =  targetMarker.getPosition();
    this.infoWindow = new AMap.InfoWindow({
        position: position,
        offset: new AMap.Pixel(0, -35),
        content: item.companyName
    });
    this.infoWindow.open(this.map);
},
复制代码
// 企业鼠标离开
matchingenterprisemouseleave(item,index) {
    this.activemetchmouseenter = "";
    let targetMarker = {};
    for (let i = 0; i < this.markers.length; i++) {
        let id = this.markers[i].getExtData().id;
        if(id == index){
            targetMarker = this.markers[i];
            break;
        }
    }
    let markerContent = '' +
        '<div class="custom-content-marker" style="position: relative;">' +
        '   <img src="//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png" style="width: 25px;height: 34px">' +
        '<div style="position: absolute;left: 9px;top: 0;margin: auto;color: #ffffff">'+ index +'</div>'+
        '</div>';
    // targetMarker.setIcon('//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png');
    targetMarker.setContent(markerContent)
    this.map.remove(this.infoWindow);
},
复制代码
// 企业点击
matchingenterpriseclick(item,index) {
    this.activeState3 = true;
    this.activeState1 = false;
    this.activeState = false;
    this.itemList = item;
    // this.map.remove(overlayGroups);
    let geocoder = new AMap.Geocoder({
        city: '全国', //城市设为北京,默认:“全国”
    });
    geocoder.getLocation(item.address, (status, result) => {
        this.map.setCenter(result.geocodes[0].location); //设置地图中心点
        this.map.setZoom(30); // 缩放级别
    })
},
复制代码

具体代码


以上所述就是小编给大家介绍的《VUE 记一次高德地图和Echarts(中国地图)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

创新者的解答

创新者的解答

【美】克莱顿•克里斯坦森、【加】迈克尔·雷纳 / 中信出版社 / 2013-10-10 / 49.00

《创新者的解答》讲述为了追求创新成长机会,美国电信巨子AT&T在短短10年间,总共耗费了500亿美元。企业为了保持成功记录,会面对成长的压力以达成持续获利的目标。但是如果追求成长的方向出现偏误,后果往往比没有成长更糟。因此,如何创新,并选对正确方向,是每个企业最大的难题。 因此,如何创新,并导向何种方向,便在于创新结果的可预测性─而此可预测性则来自于正确的理论依据。在《创新者的解答》中,两位......一起来看看 《创新者的解答》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

MD5 加密
MD5 加密

MD5 加密工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具