

<!-- 
/**
  * 高德地图组件
  *	@example1: 
		1, 引入
			import cuAmap from '@/components/AMap';

		2, 注册
			export default {
				components: {
					cuAmap
				},
				data() {
					return {
						amapinfo:{
							zoom:6,
							//longitude: 120.651884,
							//latitude: 36.962533,
						}
					}
				},
			}
		
		3, 创建
			<cu-amap 
				ref="amap" 
				//:mapinfo="amapinfo"
				//:onload="amapOnload" 
				//@click="mapClick" 
				:options="amapOptions()"
				//:parent="_self"
			/>

		4, onload [Function] 回调函数, 地图的显示: {如果设置了回调函数不需要初始化地图, 否则要初始化}
			export default {
				methods: {
					#amapOnload(cmap){
						this.mapOnload && this.mapOnload()
					},
					amapOptions(cmap){
						var self = this;
						return {
							zoom:6,
							center:[107.260044, 36.737982],
							//showLabel: true,
							//pitch: 40,
							onload: function(cmap){
								console.log('onload ________________ ', self, cmap);
								self.cmap = cmap;
							},
							click: function(e, cmap){
								console.log('click ________________ ', cmap);
							},
						};
					},
				}
			}

		 5, || 初始化
			var opts = {
				center:[107.260044, 36.737982],
				showLabel: true,
				pitch: 40,
				zoom: 4,
				mapStyle: 'amap://styles/blue',
			};
			var cmap = this.$refs.amap.init(opts);

			// 使用
			cmap.addMarker({{lnglat:[item.longitude, item.latitude], draggable:true,dragend: function(e){}});

  * @author: Kimber
  * @updatetime: 2022/5/13(周五)
  * @createtime: 2021/7/3
  */
-->


<template>
  <div id="A_Map" class="amap">amap</div>
</template>
<script>
export default {
  name: "amap",
  data() {
    return {
      icons: {
        red1: "https://webapi.amap.com/theme/v1.3/markers/n/mark_rs.png",
        red2: "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png",
        default1: "https://webapi.amap.com/theme/v1.3/markers/n/mark_bs.png",
        default2:
          "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
      },
      Markers: {},
    };
  },
  props: {
    options: {
      type: Object,
      default: {},
    },
    parent: {
      type: Object,
    },
  },
  watch: {},
  created() {
    var that = this;

    /**
	  * 初始化地图
	  * @param: {Object} options  {
			center:[107.260044, 36.737982],
			showLabel: true,
			pitch: 40,
			zoom: 4,
			// (normal(标准), dark(幻影黑), light(月光银), whitesmoke(远山黛), fresh(草色青), grey(雅士灰), graffiti(涂鸦), macaron(马卡龙), blue(靛青蓝), darkblue(极夜蓝), wine(酱籽))
			mapStyle: 'amap://styles/grey',
		};
	  *	@example1: var camap = this.$refs.amap.init(options);
	  * @return: 
	  * @author: Kimber
	  * @updatetime: 2021/7/15(周四)
	  * @createtime: 2021/7/15(周四)
	  */
    that.init = function (options, callback) {
      options = options ||
        this.options || {
          resizeEnable: true, // 是否监控地图容器尺寸变化
          zoom: 4, // 初始化地图层级
          center: [122.081977, 37.50653], // 初始化地图中心点

          //viewMode:'3D',
          //pitch:60,
          //rotation:-35,
          //features:['bg','road','point'],//隐藏默认楼块
          //mapStyle:'amap://styles/light',
          //layers: [new AMap.TileLayer.Satellite(), new AMap.Buildings({
          //'zooms':[16,18],
          //'zIndex':10,
          //'heightFactor':2	//2倍于默认高度，3D下有效
          //})],
        };
      // 卫星地图条件
      if (options.satellite) {
        var Satellite = new AMap.TileLayer.Satellite();
        (options.layers && options.layers.push(Satellite)) ||
          (options.layers = [Satellite]);

        /* var disCountry = new AMap.DistrictLayer.World({
					zIndex: 1,
					rejectMapMask: true
				}); */
        //options.layers.push(disCountry);
        options.layers.push(new AMap.TileLayer.RoadNet({ zIndex: 7 }));
      }

      var Map = new AMap.Map("A_Map", options);
      Map.on("click", function (ev) {
        // 触发事件的对象
        var target = ev.target;
        // 触发事件的地理坐标，AMap.LngLat 类型
        var lnglat = ev.lnglat;
        // 触发事件的像素坐标，AMap.Pixel 类型
        var pixel = ev.pixel;
        // 触发事件类型
        var type = ev.type;

        if (type === "click") {
          //that.$emit('click', ev, Map, that);
          that.options.click && that.options.click.call(that.parent, ev, that);
        }
      });

      /* Map.on('zoomstart', function(e){
			});
			Map.on('zoomend', function(e){
			}); */

      that.Map = Map;

      callback && callback.call(that, Map);

      return that;
    };

    that.$nextTick(() => {
      setTimeout(function () {
        var self = that.init();
        that.options.onload &&
          that.options.onload.call(that.parent, self, AMap);
      }, 300);
    });
  },
  mounted() {},
  methods: {
    /**
	  * 添加标记
	  * @param: {Object} options []
	  *	@example1: this.$refs.amap.addMarker({});
	  * @example2: 
			camap.addMarker({
				lnglat:[data.lng, data.lat],
				title:'',
				draggable:true,
				dragend: function(e){
					var lnglat = e.lnglat;
					camap.deGeocode([lnglat.lng, lnglat.lat], function(addr){
						that.form.item.lng = lnglat.lng;
						that.form.item.lat = lnglat.lat;
						that.form.item.address = addr;
					});
				},
			});
	  * @method: Kimber
	  * @return: 
	  * @updatetime: 2022/5/13(周五)
	  * @createtime: 2021/6/11
	  */
    addMarker(param) {
      /* if(this.marker){
				this.removeMarker()
			}; */
      if (param.lnglat && param.lnglat[0]) {
        var icon = this.icons[param.icon];
        var marker = (this.marker = new AMap.Marker({
          icon: icon,
          map: this.Map,
          position: param.lnglat, // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
          title: param.title,
          draggable: param.draggable,
          extData: param.extData,
        }));
        param.dragging && marker.on("dragging", param.dragging);
        param.dragend && marker.on("dragend", param.dragend);

        // 缓存
        marker.id = marker._amap_id;
        this.Markers[marker.id] = marker;
        return marker;
      }
    },
    // amap.removeMarker()
    removeMarker(marker) {
      marker = marker || this.marker;
      marker && this.Map.remove(marker);
      delete this.marker;
    },
    setTargetMarker(tag) {
      this.tagMarker = tag;
    },
    getTargetMarker() {
      return this.tagMarker;
    },
    getMarkerById(id) {
      this.Markers[~~id];
    },

    createInfoWindow(opts) {
      var infoWindow = new AMap.InfoWindow(opts);
      infoWindow.Map = this.Map;
      return infoWindow;
    },

    /**
     * 地理位置解码
     * @param: {Array} lnglat [longitude, latitude]
     *	@example1: this.$refs.amap.deGeocode([lnglat.lng, lnglat.lat], function(addr){});
     * @method: Kimber
     * @return:
     * @create: 2021/6/11
     */
    deGeocode(lnglat, fn) {
      //AMap.service('AMap.Geocoder', function() {
      AMap.plugin("AMap.Geocoder", function () {
        var geocoder = new AMap.Geocoder({});
        geocoder.getAddress(lnglat, function (status, result) {
          if (status === "complete" && result.info === "OK") {
            //var address = result.regeocode.formattedAddress;
            var addrObj = result.regeocode.addressComponent || {};
            var address =
              addrObj.province +
              addrObj.city +
              addrObj.district +
              addrObj.township;
            fn && fn(address, addrObj);
          } else {
          }
        });
      });
    },
    /**
     * 设置中心点
     * @param: {Arrar} arr
     *	@example1: this.$refs.amap.setCenter([lng, lat]);
     * @createtime: 2021/7/2
     */
    setCenter: function (arr) {
      this.Map.setCenter(arr);
    },
    /**
     * 根据中心点 marker 自适应缩放
     * @param: {Arrar} arr
     *	@example1: this.$refs.amap.setFitView(marker);
     * @createtime: 2021/7/3
     */
    setFitView: function (marker) {
      this.Map.setFitView(marker);
    },
    /**
     * 按地址定位坐标
     * @param: {String} str
     *	@example1: this.$refs.amap.addressSearch(addr).then((res) => {});
     * @createtime: 2021/7/3
     */
    addressSearch: function (str) {
      return new Promise(function (resolve, reject) {
        // 实例化Autocomplete
        var autoOptions = {
          city: "全国",
        };
        var autoComplete = new AMap.Autocomplete(autoOptions);
        autoComplete.search(str, function (status, result) {
          var list = result.tips || [];
          for (var item of list) {
            if (item.location) {
              return resolve(item);
            }
          }
          return resolve(list.pop());
        });
      });
    },

    /**
	  * 按区域画高亮遮罩层
	  * @param: {Object} opts 
		opts = {
			level: "province", // province(省), country(国)			在区域内搜索(行政区级别)
			city: '威海市',
			color: '#00000cc',
			strokeColor: 'rgba(7, 247, 247, 1)',
			fillColor: 'rgba(7, 247, 247, 1)',
		}
	  *	@example1:
	  * @return: 
	  * @author: Kimber
	  * @updatetime: 2021/7/15(周四)
	  * @createtime: 2021/7/15(周四)
	  */
    area3DLayer: function (opts) {
      var cMap = this.Map;
      var district = new AMap.DistrictSearch({
        subdistrict: 1,
        extensions: "all",
        level: opts.level,
      });

      district.search(opts.city, function (status, result) {
        var bounds = result.districtList[0].boundaries;
        var mask = [];
        for (var i = 0; i < bounds.length; i += 1) {
          mask.push([bounds[i]]);
        }

        //添加高度面
        var object3Dlayer = new AMap.Object3DLayer({ zIndex: 1 });
        cMap.add(object3Dlayer);
        var height = -7000;
        var wall = new AMap.Object3D.Wall({
          path: bounds,
          height: height,
          color: opts.color,
        });
        wall.transparent = true;
        object3Dlayer.add(wall);
        //添加描边
        for (var i = 0; i < bounds.length; i += 1) {
          var polygon = new AMap.Polygon({
            map: cMap,
            bubble: true,
            strokeWeight: 1,
            strokeDasharray: [10, 20],
            strokeColor: opts.strokeColor || "rgba(7, 247, 247, 1)",
            fillColor: opts.fillColor || "rgba(7, 247, 247, 1)",
            fillOpacity: 0.5,
            path: bounds[i],
          });
        }
      });
    },

    /**
	  * 按区域画高亮遮罩层
	  * @param: {List} ['110000', '130000', '410000', '370000'] 
		amapOptions(){
			var self = this;
			var provItems = {
				'110000':6.5,	// 北京
				'130000':6.5,	// 河北
				'410000':7.5,	//河南
				'370000':7.0,	//山东
			};
			var provList = Object.keys(provItems);

			return {
				viewMode:'3D',
				zooms: [4, 6],
				center:[106.122082, 33.719192],
				zoom: 4,
				isHotspot:false,
				defaultCursor:'pointer',
				//layers:[Layers.disProvince],
				mapStyle:'false',
				onload: function(cmap, AMap){
					self.Layers = new cmap.DistrictLayers(provList);
					cmap.Map.setLayers([self.Layers.disProvince])
				},
				click: function(ev, cmap){
					var px = ev.pixel;
					var props = self.Layers.disProvince.getDistrictByContainerPos(px);
					var pro_code = props && props.adcode_pro + '' || '';
					var index = self.Layers.codeList.indexOf(pro_code);
					if(props && index > -1){
						self.Layers.set(pro_code);
					};
				},
			};
	  *	@example1:
	  * @return: 
	  * @author: Kimber
	  * @updatetime: 2022/10/5(周三)
	  * @createtime: 2022/10/5(周三)
	  */
    DistrictLayers: function (codeList) {
		/* var GDPSpeed = {
			'520000':10,//贵州
			'540000':10,//西藏
			'530000':8.5,//云南 
			'500000':8.5,//重庆
			'360000':8.5,//江西
			'340000':8.0,//安徽
			'510000':7.5,//四川
			'350000':8.5,//福建
			'430000':8.0,//湖南
			'420000':7.5, //湖北
			'410000':7.5,//河南
			'330000':7.0,//浙江
			'640000':7.5,//宁夏
			'650000':7.0,//新疆
			'440000':7.0,//广东
			'370000':7.0,//山东
			'450000':7.3,//广西
			'630000':7.0,//青海
			'320000':7.0,//江苏
			'140000':6.5,//山西
			'460000':7,// 海南
			'310000':6.5,//上海
			'110000':6.5, // 北京
			'130000':6.5, // 河北
			'230000':6, // 黑龙江
			'220000':6,// 吉林
			'210000':6.5, //辽宁
			'150000':6.5,//内蒙古
			'120000':5,// 天津
			'620000':6,// 甘肃
			'610000':8.5,// 甘肃
			'710000':2.64, //台湾
			'810000':3.0, //香港
			'820000':4.7 //澳门
			'110000':6.5, // 北京
			'130000':6.5, // 河北
			'410000':7.5,//河南
			'370000':7.0,//山东
		}; */
      var Widget = function () {
        this.listLayers = [];
        return this.create(codeList);
      };
      Widget.prototype = {
        create: function (codeList, color) {
          this.disProvince = this.setCountry(codeList);
          return (this.codeList = codeList), this;
        },
        setStyle: function (pro_code) {
          this.disProvince.setStyles({
            "nation-stroke": "#08fcfc", // 国界
            "coastline-stroke": "transparent", // 岛礁
            "province-stroke": "green", // 省界
            "city-stroke": "transparent", // 中国地级市边界
            "county-stroke": "rgba(255,255,255,0.5)", // 中国区县边界
            fill: function (props) {
              var adcode_pro = props.adcode_pro + "";
              //return adcode_pro === pro_code ? 'rgba(20, 120, 230, 0.8)' : 'rgba(8, 57, 123, 1)';
              return codeList.indexOf(adcode_pro) > -1
                ? (adcode_pro === pro_code && "rgba(20, 120, 230, 0.8)") ||
                    "rgba(8, 57, 123, 1)"
                : "transparent";
            },
          });
        },
        setCountry: function (codeList) {
          return new AMap.DistrictLayer.Country({
            zIndex: 10,
            SOC: "CHN",
            depth: 1,
            styles: {
              "nation-stroke": "#08fcfc",
              "coastline-stroke": "transparent",
              "province-stroke": "green",
              fill: function (props) {
                var adcode_pro = props.adcode_pro + "";
                return codeList.indexOf(adcode_pro) > -1
                  ? "rgba(8, 57, 123, 1)"
                  : "transparent";
              },
            },
          });
        },
        setProvince: function (codeList) {
          return new AMap.DistrictLayer.Province({
            zIndex: 10,
            SOC: "CHN",
            //adcode: codeList,
            depth: 1,
            styles: {
              "nation-stroke": "transparent", // 国界
              "coastline-stroke": "transparent", // 岛礁
              "province-stroke": "green", // 省界
              "city-stroke": "transparent", // 中国地级市边界
              "county-stroke": "rgba(255,255,255,0.5)", // 中国区县边界
              fill: function (props) {
                var adcode_pro = props.adcode_pro + "";
                return codeList.indexOf(adcode_pro) > -1
                  ? "rgba(8, 57, 123, 1)"
                  : "transparent";
              },
            },
          });
        },
      };
      return new Widget();
    },
  },
};
</script>
<style lang="scss" scoped>
.amap {
  height: 100%;
  width: 100%;
  background-color: transparent;
}
.amap-container {
  background-image: none;
}
</style>
<style lang="scss">
.amap-logo {
  display: none !important;
}
</style>
