首页 前端知识 vue vue-amap echarts-amap echarts 高德地图开发在线省市地图并标记点.

vue vue-amap echarts-amap echarts 高德地图开发在线省市地图并标记点.

2024-05-09 10:05:26 前端知识 前端哥 84 825 我要收藏

最终效果图:
在这里插入图片描述
首先需要引入:

1:在index.html中引入:

   <script type="text/javascript">
    window._AMapSecurityConfig = {
      securityJsCode: '自己去高德地图申请',
    }
  </script>
  <script src="https://webapi.amap.com/maps?key=高德地图官网申请key&v=1.4.15"></script>

key需要自己去高德地图官网申请.

2.在画图的vue页面引入:

import * as echarts from "echarts";
import VueAMap from "vue-amap"; //高德地图插件
import "echarts-amap";

3.开始画地图

 init() {
      let _this = this
      AMap.plugin(
        ['AMap.DistrictSearch', 'AMap.MapType', 'AMap.CustomLayer'],
        function () {
          var district = new AMap.DistrictSearch({
            extensions: 'all',
            level: 'province', //省市县对应的不同,根据自己的需求去改
          })
          district.search('河北省', function (status, result) { //河北省改成你需要的省份
            var bounds = result.districtList[0].boundaries
            var districts = result.districtList[0].districtList

            var mask = []
            for (var i = 0; i < bounds.length; i++) {
              mask.push([bounds[i]])
            }
            var myChart = echarts.init(document.getElementById('mapData')) //初始化容器

            var option = {
              animation: false,
              amap: {
                mask: mask,
                center: [116.397428, 39.90923],
                viewMode: '3D',
                zoom: 6.7,
                defaultCursor: 'auto',
              },
              series: _this.seriesData,
            }
            myChart.setOption(option)
            var map = myChart.getModel().getComponent('amap').getAMap()
            var layer = myChart.getModel().getComponent('amap').getLayer()
            var mapType = new AMap.MapType({
              defaultType: 1,
            })
            // console.log(JSON.stringify(mapType));
  
            map.addControl(mapType)
            mapType.hide()

            var LabelsData = []

            for (var i = 0; i < districts.length; i++) {
              var config = {
                name: '',
                // position: [116.12, 39.11],
                zooms: [4, 13],
                zIndex: 1,
                opacity: 1,
                text: {
                  content: '',
                  direction: 'center',
                  offset: [0, 0],
                  zooms: [3, 20],
                  style: {
                    fontSize: 12,
                    fontWeight: 'normal',
                    fillColor: '#fff',
                    strokeColor: '#fff',
                    strokeWidth: 1,
                  },
                },
              }

              var district = districts[i]
              var name = district.name

              config.text.content = name
              config.position = [district.center.lng, district.center.lat]

              LabelsData.push(config)

              var district2 = new AMap.DistrictSearch({
                extensions: 'all',
                level: 'city',
              })
             

              district2.search(name, function (status, result) {
                var bounds = result.districtList[0].boundaries
     
                for (var ii = 0; ii < bounds.length; ii++) {
                  new AMap.Polyline({
                    map: map,
                    path: bounds[ii],
                    strokeColor: '#E7D8BC',
                    strokeWeight: 2,
                  })
                }
              })
            }

            for (var i = 0; i < bounds.length; i++) {
              new AMap.Polyline({
                map: map,
                path: bounds[i],
                strokeColor: '#E7D8BC',
                strokeWeight: 6,
              })
            }

            map.on('complete', function () {
              var layer = new AMap.LabelsLayer({
                collision: false,
                animation: true,
              })

              for (var i = 0; i < LabelsData.length; i++) {
                var labelsMarker = new AMap.LabelMarker(LabelsData[i])
                layer.add(labelsMarker)
              }
              map.add(layer)
              document.getElementsByClassName(
                'amap-container'
              )[0].style.background = 'none'
            })
          })
        }
      )
    },

4.完整代码

<!--  -->
<template>
  <div class="">
    <div class="amapBox">
      <div id="mapData" ref="mapData" style="width: 96%; height: 720px"></div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";

import VueAMap from "vue-amap"; //高德地图插件
import "echarts-amap";
import imgIcon1 from "@/assets/login/1.png";
import imgIcon2 from "@/assets/login/19.png";
import imgIcon3 from "@/assets/login/1.png";
import imgIcon4 from "@/assets/login/19.png";
// import AMap from 'AMap'
// import {findFcxxListByCompanyCodeAndFdlx} from '@/api/dashboard/dashboardApi'
// let AMap = Amap;
export default {
  props: {
    mapDataList: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  data(vm) {
    return {
      mapData: null,
      goals: [
        {
          name: "风电场1",
          images: imgIcon1,
          value: [113.775669, 38.709836],
        },
        {
          name: "风电场2",
          images: imgIcon1,
          value: [114.775669, 40.709836],
        },
        {
          name: "光伏1",
          images: imgIcon2,
          value: [115.775669, 41.709836],
        },
        {
          name: "光伏2",
          symbol: "image://" + imgIcon2,

          value: [114.775669, 39.709836],
        },
      ],
      goalsTow: [],
      goalsThree: [],
      goalsfour: [],
      seriesData: [],
    };
  },
  watch: {},
  //方法集合
  methods: {
    initData() {
      console.log(VueAMap);
      this.seriesData = [
        {
          name: "点",
          type: "scatter",
          coordinateSystem: "amap",
          zlevel: 9999,

          rippleEffect: {
            brushType: "stroke",
          },
          hoverAnimation: true,
          label: {
            normal: {
                show: true,
                position: 'right',
                formatter: '{b}',
                color:'#fff',
                padding:[10,20,10,20],
                backgroundColor:'rgba(0,0,0,0.5)'
              },
            
          },
          itemStyle: {
            normal: {
              color: "#4892C2",
              shadowBlur: 12,
              shadowColor: "#fff",
            },
          },
          showAllSymbol: true,
          symbolSize: "20",
          symbol: `image://${imgIcon1}`,
          symbolRotate: 35,
          data: this.goals,
        },
        {
          name: "点",
          type: "scatter",
          coordinateSystem: "amap",
          zlevel: 9999,
          rippleEffect: {
            brushType: "stroke",
          },
          hoverAnimation: true,
          label: {
            show: false,
          },
          itemStyle: {
            normal: {
              color: "#4892C2",
              shadowBlur: 12,
              shadowColor: "#fff",
            },
          },
          showAllSymbol: true,
          symbolSize: 26,
          symbol: `image://${imgIcon2}`,
          symbolRotate: 35,
          data: this.goalsTow,
        },
        {
          name: "点",
          type: "scatter",
          coordinateSystem: "amap",
          zlevel: 9999,
          rippleEffect: {
            brushType: "stroke",
          },
          hoverAnimation: true,
          label: {
            show: false,
          },
          itemStyle: {
            normal: {
              color: "#4892C2",
              shadowBlur: 12,
              shadowColor: "#fff",
            },
          },
          showAllSymbol: true,
          symbolSize: 26,
          symbol: `image://${imgIcon3}`,
          symbolRotate: 35,
          data: this.goalsThree,
        },
        {
          name: "点",
          type: "scatter",
          coordinateSystem: "amap",
          zlevel: 9999,
          rippleEffect: {
            brushType: "stroke",
          },
          hoverAnimation: true,
          label: {
            show: false,
          },
          itemStyle: {
            normal: {
              color: "#4892C2",
              shadowBlur: 12,
              shadowColor: "#fff",
            },
          },
          showAllSymbol: true,
          symbolSize: 26,
          symbol: `image://${imgIcon4}`,
          symbolRotate: 35,
          data: this.goalsfour,
        },
      ];
      this.init();
    },
    dataReturnFn(v) {
      let that = this;
      let obj = {
        name: v.name,
        value: v.gps,
        label: {
          normal: {
            show: true,
            formatter: function (params) {
              return "{div|" + params.name + "}";
            },
            padding: [0, 0, 0, -120], //内边距属性

            rich: {
              div: {
                color: "#fff",

                padding: [5, 10, 5, 10],
                backgroundColor: "rgba(0,0,0,0.9)",
              },
            },
          },
        },
      };
      return {
        type1: () => {
          return that.goals.push(obj);
        },
        type2: () => {
          return that.goalsTow.push(obj);
        },
        type3: () => {
          return that.goalsThree.push(obj);
        },
        type4: () => {
          return that.goalsfour.push(obj);
        },
      };
    },
    handlerMapData(v, i) {
      this.dataReturnFn(v)["type" + i]();
    },
    init() {
      let _this = this;
      AMap.plugin(
        ["AMap.DistrictSearch", "AMap.MapType", "AMap.CustomLayer"],
        function () {
          var district = new AMap.DistrictSearch({
            extensions: "all",
            level: "province",
          });
          district.search("河北省", function (status, result) {
            var bounds = result.districtList[0].boundaries;
            var districts = result.districtList[0].districtList;

            var mask = [];
            for (var i = 0; i < bounds.length; i++) {
              mask.push([bounds[i]]);
            }
            var myChart = echarts.init(document.getElementById("mapData"));

            console.log(mask);

            console.log(districts);
            var option = {
              animation: false,
              amap: {
                mask: mask,
                center: [116.397428, 39.90923],
                viewMode: "3D",
                zoom: 6.7,
                defaultCursor: "auto",
              },
              series: _this.seriesData,
            };
            myChart.setOption(option);
            var map = myChart.getModel().getComponent("amap").getAMap();
            var layer = myChart.getModel().getComponent("amap").getLayer();
            console.log(layer);
            var mapType = new AMap.MapType({
              defaultType: 1,
            });
            // console.log(JSON.stringify(mapType));

            map.addControl(mapType);
            mapType.hide();

            var LabelsData = [];

            for (let i = 0; i < districts.length; i++) {
              var config = {
                name: "",
                zooms: [4, 13],
                zIndex: 1,
                opacity: 1,
                text: {
                  content: "",
                  direction: "center",
                  offset: [0, 0],
                  zooms: [3, 20],
                  style: {
                    fontSize: 12,
                    fontWeight: "normal",
                    fillColor: "#fff",
                    strokeColor: "#fff",
                    strokeWidth: 1,
                  },
                },
              };

              var district = districts[i];
              var name = district.name;

              config.text.content = name;
              config.position = [district.center.lng, district.center.lat];

              LabelsData.push(config);

              var district2 = new AMap.DistrictSearch({
                extensions: "all",
                level: "city",
              });

              district2.search(name, function (status, result) {
                var bounds = result.districtList[0].boundaries;

                for (var ii = 0; ii < bounds.length; ii++) {
                  new AMap.Polyline({
                    map: map,
                    path: bounds[ii],
                    strokeColor: "#E7D8BC",
                    strokeWeight: 2,
                  });
                }
              });
            }

            for (let i = 0; i < bounds.length; i++) {
              new AMap.Polyline({
                map: map,
                path: bounds[i],
                strokeColor: "#E7D8BC",
                strokeWeight: 6,
              });
            }

            map.on("complete", function () {
              var layer = new AMap.LabelsLayer({
                collision: false,
                animation: true,
              });

              for (var i = 0; i < LabelsData.length; i++) {
                var labelsMarker = new AMap.LabelMarker(LabelsData[i]);
                layer.add(labelsMarker);
              }
              map.add(layer);
              document.getElementsByClassName(
                "amap-container"
              )[0].style.background = "none";
            });
          });
        }
      );
    },
  },

  //生命周期 - 挂载完成(可以访问DOM元素)
  mounted() {
    this.initData();

    // const mapContainer = this.$refs.mapData;
    // console.log(mapContainer);
    // const map = new Map({
    //   layers: mapconfig.streetmap(), //在mapconfig.js封装的
    //   // controls: [FullScreen, ScaleLine, Zoom],
    //   target: mapContainer,
    //   view: new View({
    //     projection: "EPSG:4326",
    //     center: [116.397428, 39.90923],
    //     zoom: 11,
    //   }),
    // });
    //  // 添加鼠标点击事件
    // map.on("click", this.mapClick);
    // // 添加鼠标经过事件
    // map.on("pointermove", this.mapPointerMove);
    // // 保存地图
    // this.mapData = map;
  },
};
</script>
<style scoped>
.amapBox {
  display: flex;
  justify-content: center;
  height: 500px;
  width: 100%;
  position: relative;
  top: -40px;
}
::v-deep .amap-logo {
  display: none !important;
}
::v-deep .amap-copyright {
  display: none !important;
}

.amap-marker-label {
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  border-radius: 10px;
  border: none;
  -webkit-box-shadow: 1px 2px 4px #cccccc;
  -moz-box-shadow: 1px 2px 4px #cccccc;
  box-shadow: 1px 2px 4px #cccccc;
}
</style>

上述就是实现的功能,写的不好。欢迎补充。转载请标明出处,谢谢

转载请注明出处或者链接地址:https://www.qianduange.cn//article/7690.html
标签
评论
会员中心 联系我 留言建议 回顶部
复制成功!