5
  1. 全地区展示/点聚合
  2. 单独区域展示
  3. 行政区划分
  4. 自定义图层
  5. 样图展示

一、全地区展示/点聚合
注意点:
1、把 AMap.Map 绑定dom放到 search 行政查询之外;
2、使用 AMap.MarkerClusterer 插件点聚合
3、不用再把点位 map.add

/* 加载地图 */
async getMaps() {
  this.loading = true;
  await MapLoader().then(
    (AMap) => {
      const map = new AMap.Map("map_three", {
        showLabel: true,
        mapStyle: "amap://styles/ccab8afcf9c843aefac72ff71d705eb4",
        center: [114.085947, 22.547],
        viewMode: "3D",
        labelzIndex: 130,
        pitch: 30,
        zoom: 11.5,
        zooms: [11, 18],
        features: ["road", "point", "bg"],
      });
      const district = new AMap.DistrictSearch({
        subdistrict: 0,
        extensions: "all",
        level: "district",
      });
      district.search("宝安区", (status, result) => {
        const [bounds,mask] = [result.districtList[0].boundaries,[]]
        if (bounds) {
          for (let i = 0, l = bounds.length; i < l; i++) {
            //生成行政区划polygon
            let polygon = new AMap.Polygon({
              map: map,
              strokeWeight: 1,
              path: bounds[i],
              fillOpacity: 0.25,
              fillColor: "#09b8bf",
              strokeColor: "#09b8bf",
            });
            mask.push(polygon);
          }
        }
        map.add(mask);
        map.setFitView(mask); //视口自适应
       
        //插件:行政区图层、点聚合
        AMap.plugin(["AMap.DistrictLayer"], function () {
          const disProvince = new AMap.DistrictLayer.Province({
            zIndex: 12,
            depth: 2,
            styles: {
              fill: function (properties) {
                let adcode = properties.adcode;
                return getColorByAdcode(adcode);
              },
              "province-stroke": "#09b8bf",
              "city-stroke": "#09b8bf",
              "county-stroke": "#09b8bf", //线条颜色
            },
          });
          disProvince.setMap(map);
        });
        //随机颜色
        const getColorByAdcode = (adcode) => {
          const colors = {};
          if (!colors[adcode]) colors[adcode] = "rgba(7,111,142,0.7)";
          return colors[adcode];
        };
        map.on("click", () => {
          this.maps.infowindow.close();
        });
        this.maps.map = map;
        this.maps.AMap = AMap;
        this.drawStaion(AMap, map);
      });
    },
    (e) => {
      console.error("地图加载失败", e);
    }
  );
},

/* 生成地图点位 */
async drawStaion(AMap, map, pointList=this.maps.pointList) {
  const [data,markers] = [pointList,[]];
  let infowindow = null;
  for (let i in data) {
    const curPoint = data[i];
    //点位状态颜色
    const status = this.getStatus(curPoint.status);
    //点位模板
    const contents = this.setMapInfo(status, curPoint, curPoint.status);
    //弹窗模板
    const windowPopup = this.openPopup(curPoint, this);

    //点位实例
    const marker = new AMap.Marker({
      content: contents,
      position: [curPoint.longitude, curPoint.latitude],
    });
    //弹窗实例
    infowindow = new AMap.InfoWindow({
      isCustom: true,
      anchor: "bottom-center",
      offset: new AMap.Pixel(5, -12),
    });
    marker.on("click", (e) => {
      //防止每项变成遍历的最后一个
      infowindow.setContent(windowPopup.$el);
      infowindow.open(map, marker.getPosition());
    });
    markers.push(marker);
    this.maps.infowindow = infowindow;
    this.markers = markers;
  }

  /* 点聚合部分 */
  AMap.plugin(["AMap.MarkerClusterer"],()=>{
        new AMap.MarkerClusterer(map, markers, {
          gridSize: 80,
          renderClusterMarker: _renderClusterMarker,
        });
        const count = markers.length;
      var _renderClusterMarker = function (context) {
        var factor = Math.pow(context.count / count, 1 / 18);
        var div = document.createElement("div");
        var Hue = 180 - factor * 180;
        var bgColor = "hsla(" + Hue + ",100%,50%,0.7)";
        var fontColor = "hsla(" + Hue + ",100%,20%,1)";
        var borderColor = "hsla(" + Hue + ",100%,40%,1)";
        var shadowColor = "hsla(" + Hue + ",100%,50%,1)";
        div.style.backgroundColor = bgColor;
        var size = Math.round(30 + Math.pow(context.count / count, 1 / 5) * 20);
        div.style.width = div.style.height = size + "px";
        div.style.border = "solid 1px " + borderColor;
        div.style.borderRadius = size / 2 + "px";
        div.style.boxShadow = "0 0 1px " + shadowColor;
        div.innerHTML = context.count;
        div.style.lineHeight = size + "px";
        div.style.color = fontColor;
        div.style.fontSize = "14px";
        div.style.textAlign = "center";
        context.marker.setOffset(new AMap.Pixel(-size / 2, -size / 2));
        context.marker.setContent(div);
      };
  })

  //map.add(markers);//不用添加进map
  this.loading = false;
},

二、单独地区展示,区域外不显示
注意点:
1、把 AMap.Map 绑定 dom 的部分放进进 search 查询函数体内;
2、AMap.DistrictSearch 查询中的 level 属性,展示城市的就改成 city,展示区域就改成 district。(高德地图官网都有查询等级,根据需要对应更改一下就好了)

const district = new AMap.DistrictSearch({
    subdistrict: 1,
    extensions: "all",
    level: "district",
    features: ["road", "point", "bg"], //设置地图显示内容
  });
district.search("宝安区", (status, result) => {
    const [bounds,mask] = [result.districtList[0].boundaries,[]]
    for (let i = 0; i < bounds.length; i += 1) mask.push([bounds[i]]);
    //重点:把绑定的元素放进查询里
    const maps = new AMap.Map("map", {
      mask: mask,
      mapStyle: "amap://styles/42828ca67777d22056d80019d1c4f90f",
      center: [113.873549, 22.642423],
      viewMode: "3D",
      showLabel: true,
      labelzIndex: 130,
      pitch: 30,
      zooms: [12, 18],
    });
    
    //异步加载插件
    AMap.plugin(["AMap.DistrictLayer"], ()=>{
      const disProvince = new AMap.DistrictLayer.Province({
        zIndex: 12,
        depth: 2,
        styles: {
          fill: (properties)=>{
            var adcode = properties.adcode;
            return getColorByAdcode(adcode);
          },
          "county-stroke": "#09b8bf", //线条颜色
        },
      });
      disProvince.setMap(maps);
    });
    //随机颜色
    function getColorByAdcode(adcode) {
      const colors = {};
      if (!colors[adcode]) colors[adcode] = "transparent";
      return colors[adcode];
    };
    //this.maps.map = maps;
    //关闭信息窗口
    maps.on("click", () => {
      this.infoWindow.close();
    });
});

三、行政区划分
注意点:
1、new AMap.DistrictSearch 查询中把 level 值 "city"
2、AMap.DistrictLayer.Province 添加 adcode 子行政地区码
3、在2021年12月02日以后申请的 key 需要配合安全密钥一起使用,以下在index.html文件中引入。

<script type="text/javascript">
      window._AMapSecurityConfig = {securityJsCode: '密匙'}
    </script>
    <script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=key值&plugin=AMap.DistrictSearch"></script>
async getMaps() {
  this.loading = true;
  await MapLoader().then(
    (AMap) => {
      const map = new AMap.Map("map_three", {
        showLabel: true,
        mapStyle: "amap://styles/ccab8afcf9c843aefac72ff71d705eb4",
        center: [114.085947, 22.547],
        viewMode: "3D",
        labelzIndex: 130,
        pitch: 30,
        zoom: 11.5,
        zooms: [11, 18],
        features: ["road", "point", "bg"],
      });
      const district = new AMap.DistrictSearch({
        subdistrict: 0,
        extensions: "all",
        level: "city",//城市
      });
      district.search("深圳市", (status, result) => {
        const [bounds,mask] = [result.districtList[0].boundaries,[]]
        if (bounds) {
          for (let i = 0, l = bounds.length; i < l; i++) {
            //生成行政区划polygon
            let polygon = new AMap.Polygon({
              map: map,
              strokeWeight: 1,
              path: bounds[i],
              fillOpacity: 0.25,
              fillColor: "#09b8bf",
              strokeColor: "#09b8bf",
            });
            mask.push(polygon);
          }
        }
        map.add(mask);
        map.setFitView(mask); //视口自适应

        AMap.plugin(["AMap.DistrictLayer"], function () {
          const disProvince = new AMap.DistrictLayer.Province({
            zIndex: 12,
            depth: 2,
            adcode: ["440306","440307","440308"],//重点:添加要划分的子行政区码
            styles: {
              fill: function (properties) {
                let adcode = properties.adcode;
                return getColorByAdcode(adcode);
              },
              "province-stroke": "#09b8bf",
              "city-stroke": "#09b8bf",
              "county-stroke": "#09b8bf", //线条颜色
            },
          });
          disProvince.setMap(map);
        });
        //随机颜色
        const getColorByAdcode = (adcode) => {
          const colors = {};
          if (!colors[adcode]) colors[adcode] = '#' + parseInt(0x1000000 * Math.random()).toString(16).padStart(6, '0');
          return colors[adcode];
        };
        map.on("click", () => {
          this.maps.infowindow.close();
        });
      });
    },
    (e) => {
      console.error("地图加载失败", e);
    }
  );
},

四、自定义图层(图片)
注意点:使用 AMap.ImageLayer 添加到 AMap.Map 的 layers 属性中

async getMaps() {
  this.loading = true;
  await MapLoader().then(
    (AMap) => {
      //引入图片图层
      const imageLayer = new AMap.ImageLayer({
        url: require("@/assets/images/home/map_bg2-2.png"),
        bounds: new AMap.Bounds(
          [113.748587, 22.515094],//左下
          [113.990000, 22.860618]//右上
        ),
        zooms: [11, 18],
      });

      const map = new AMap.Map("map_five", {
        showLabel: true,
        mapStyle: "amap://styles/ccab8afcf9c843aefac72ff71d705eb4",
        viewMode: "3D",
        labelzIndex: 130,
        pitch: 30,
        rotateEnable: true,
        center: [113.873549, 22.642423],
        resizeEnable: true,
        zooms: [11, 18],
        features: ["road", "point", "bg"],
        layers: [new AMap.TileLayer(), imageLayer],//图层实例放到此处
      });
      map.on("click", (e) => {
        this.maps.infowindow.close();
      });
      this.maps.map = map;
      this.maps.AMap = AMap;
      let arr = [];
      arr = this.maps.pointList.filter((item) => {
        return this.checkList.includes(item.label);
      });
      this.drawStaion(AMap, map, arr);
    },
    (e) => {
      console.error("地图加载失败", e);
    }
  );
},

五、样图展示
1、全地区展示/点聚合

2、单独区域展示

3、行政区划分

4、自定义图层


九霄
151 声望12 粉丝

记录开发以来,遇到的一些问题...