<template>
  <baidu-map class="map" :center="center" :zoom="zoom" @ready="handler" @click="mapClick(this, $event)">
    <!--  缩放  -->
    <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
  </baidu-map>
</template>

<script>
  export default {
    data() {
      return {
        center: {
          lng: 113.764742,
          lat: 23.046996
        },  // 经纬度
        zoom: 12, // 地图展示级别
        pointList: [],
        pickPoint: null
      }
    },
    methods: {
      handler({map}) {
        // 定位
        this.geolocation(map);
        // 产生随机点
        const bounds = map.getBounds();
        const sw = bounds.getSouthWest();
        const ne = bounds.getNorthEast();
        const lngSpan = Math.abs(sw.lng - ne.lng);
        const latSpan = Math.abs(ne.lat - sw.lat);
        for (let i = 0; i < 5; i++) {
          const point = {
            title: '分公司' + (i + 1),
            point: {
              lng: sw.lng + lngSpan * (Math.random() * 0.7),
              lat: ne.lat - latSpan * (Math.random() * 0.7)
            }
          };
          this.pointList.push(point);
        }
        this.addMarker(map);
      },
      mapClick(map, e) {
        const point = e.point;
        if (this.pickPoint) {
          map.removeOverlay(this.pickPoint);
        }
        console.log(point.lng + ',' + point.lat);
        const p = new BMap.Point(point.lng, point.lat);
        this.pickPoint = new BMap.Marker(p);
        map.addOverlay(this.pickPoint);
      },
      addMarker(map) {
        for (const item of this.pointList) {
          const point = new BMap.Point(item.point.lng, item.point.lat);
          const mk = new BMap.Marker(point);
          const label = new BMap.Label(item.title);
          label.setOffset(new BMap.Size(15, -15));
          label.setStyle({
            'border-radius': '5px',
            border: '0px',
            'background-color': '#FFFFFF11',
            color: 'red',
            'font-family': '黑体',
            'font-weight': 'bold',
            'font-size': '16px'
          });
          mk.setLabel(label);
          map.addOverlay(mk);
        }
      },
      geolocation(map) {
        const geolocation = new BMap.Geolocation();
        geolocation.enableSDKLocation();
        geolocation.getCurrentPosition(function (r) {
          if (this.getStatus() === BMAP_STATUS_SUCCESS) {
            // const mk = new BMap.Marker(r.point);
            // map.addOverlay(mk);
            map.panTo(r.point);
            console.log('您的位置：' + r.point.lng + ',' + r.point.lat);
          } else {
            alert('failed' + this.getStatus());
          }
        });
      }
    }
  }
</script>

<style scoped>
  .map {
    width: 100%;
    height: 500px;
  }
</style>
