<template>
  <div class="map-container" id="map-container"></div>
</template>

<script>
import $L from "leaflet"; //引入地图api
import "leaflet/dist/leaflet.css"; //引入地图样式

// 解决 leaflet 默认 maker 无法显示的问题
import icon from "leaflet/dist/images/marker-icon.png";
import iconShadow from "leaflet/dist/images/marker-shadow.png";

export default {
  name: "maptest",
  components: {},
  data() {
    //私有变量
    return {
      map: null,
      layer: null
    };
  },
  beforeCreate() {
    console.log("beforeCreate");
  },
  created() {
    console.log("created");
  },
  beforeMount() {
    console.log("beforeMount");
  },
  mounted() {
    console.log("mounted");

    this.map = $L.map("map-container", {}); //声明地图对象。
    //在函数内访问组件的私有变量，怎么实现？
    //用_self替换this
    this.addMarker([30, 114]);
    this.addMarker([30.5, 114.5]);
    this.addPolyline([
      [30, 114],
      [30.5, 114.5]
    ]);
    this.addPolygon([[30, 114], [30.5, 114.5],[31, 114]]);
    this.addLayer();
    this.map.setView([30, 114], 8); //设置地图的中心和缩放等级
    console.log(this.map);
  },
  methods: {
    addLayer:  function() {
      this.layer =  $L.tileLayer(
        "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
        {}
      ); //声明一个瓦片图层。
      this.layer.addTo(this.map); //将图层添加到地图
      console.log(this.layer);
    },
    addMarker: function(coordinate) {
      let DefaultIcon = $L.icon({
        iconUrl: icon,
        shadowUrl: iconShadow
      });

      let marker = $L.marker($L.latLng(coordinate[0], coordinate[1]), {
        icon: DefaultIcon
      });
      marker.addTo(this.map);
    },
    addPolyline(linePath) {
      let polyline = $L.polyline(linePath, {
        stroke: true,
        color: "#0085fb",
        weight: 4,
        opacity: 0.7 //不透明度
      });
      polyline.addTo(this.map);
    },
    addPolygon(areapath) {
      let polygon = $L.polygon(areapath, {});
      polygon.addTo(this.map);
    }

    //
  },
  beforeDestroy() {
    console.log("beforeDestroy");
  },
  destroyed() {
    console.log("destroyed");
  }
};
</script>
<style lang="less">
.map-container {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}
</style>
