<template>
  <div :id="'map' + withKeyId" class="mars2d-container"></div>
</template>
<script>
import * as mars2d from "mars2d";
export default {
  props: {
    url: {
      type: String,
      default: "",
    },
    withKeyId: {
      type: String,
      default: "mars2dMap",
    },
    options: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {};
  },
  mounted() {
    this.initMap();
  },
  beforeDestroy() {
    const map = this[`map${this.withKeyId}`];
    if (map) {
      map.destroy();
      delete this[`map${this.withKeyId}`];
    }
  },
  methods: {
    async initMap() {
      // 获取配置
      let mapOptions;
      if (this.url) {
        // 存在url时才读取
        mapOptions = await mars2d.Util.fetchJson({ url: this.url });
        if (mapOptions.map3d) {
          mapOptions = mapOptions.map3d;
        }
        if (this.options) {
          mapOptions = mars2d.Util.merge(mapOptions, this.options); // 合并配置
        }
      } else if (this.options) {
        mapOptions = this.options;
      }

      this[`map${this.withKeyId}`] = new mars2d.Map(
        "map" + this.withKeyId,
        mapOptions
      );

      this.$emit("onload", this[`map${this.withKeyId}`]);
    },
  },
};
</script>
<style>
.mars2d-container {
  height: 100%;
  overflow: hidden;
}
</style>
