<template>
  <div :id="mapId" class="__map"></div>
</template>

<script>
import mapboxgl from "mapbox-gl";
import { register } from "./config/map.js";
import style from "./config/index.js";
export default {
  props: {
    center: {
      type: Array,
      default: () => [110, 30],
    },
    zoom: {
      type: Number,
      default: 2,
    },
    mapId: {
      // 接收图层容器的ID
      type: String || undefined,
      default: "map",
    },
  },
  data() {
    return {
      map: null,
    };
  },
  mounted() {
    this.initMap();
  },
  methods: {
    initMap() {
      this.map = new mapboxgl.Map({
        container: this.mapId,
        zoom: this.zoom,
        center: [110, 30],
        // style: "mapbox://styles/mapbox/dark-v10",
        style: {
          version: 8,
          center: [110, 36],
          zoom: 3,
          sources: {},
          layers: [],
          glyphs: "./fonts/{fontstack}/{range}.pbf",
        },
        maxZoom: 19.9,
        minZoom: 0.1,
        // dragRotate: false,
        trackResize: true,
        attributionControl: false,
        preserveDrawingBuffer: true,
        renderWorldCopies: false, // 地图不重复
        // style
      });
      this.map.on("load", () => {
        let map = this.map;
        window.map = this.map;

        // 添加新的地图实例方法, 初始化相关状态
        register(mapboxgl.Map.prototype);
        // map._initMapState({
        //   center: this.center,
        //   zoom: this.zoom
        // })
        // console.log()
        map.setBaseMap({ sources: style.sources, layers: style.layers });
        // 添加source
        Object.entries(style.sources).forEach((item) => {
          map.addSource(item[0], item[1]);
        });

        // 添加layers
        style.layers.forEach((item) => {
          map.addLayer(item);
        });
        this.$emit("onload", map);
      });
    },
  },
};
</script>

<style lang="less" scoped>
.__map {
  position: absolute;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

// .pop-class {
//   background-color: red;
// }

.mapboxgl-ctrl {
  display: none !important;
}
</style>
