<template>
  <div class="amap-page-container">
    <el-amap-search-box
      class="search-box"
      :search-option="searchOption"
      :on-search-result="onSearchResult"
    >
    </el-amap-search-box>
    <el-amap
      vid="amapDemo"
      :center="mapCenter"
      :zoom="zoom"
      class="amap-demo"
      :plugin="plugin"
      :events="events"
    >
      <el-amap-marker
        vid="component-marker"
        :position="[lng, lat]"
      >
      </el-amap-marker>
    </el-amap>
    <div class="toolbar">
      坐标: {{ lng }}, {{ lat }}
      <el-button type="primary" @click="mapConfirm(true)">确定</el-button>
      <el-button type="info" @click="mapConfirm(false)">取消</el-button>
    </div>
  </div>
</template>
<script>
import Vue from 'vue';
import VueAMap from 'vue-amap';
Vue.use(VueAMap);
VueAMap.initAMapApiLoader({
  key: '2719fe261fee06a08dcb4980990879da',
  plugin: ['ToolBar'],
  v: '1.4.4',
  uiVersion: '1.0.11',
});
export default {
  data() {
    const self = this;
    return {
      lng: 0,
      lat: 0,
      zoom: 13,
      center: [114.509327, 38.046555],
      plugin: [
        {
          pName: 'ToolBar',
          events: {
            init(instance) {
              // console.log(instance);
            },
          },
        },
      ],
      markers: [],
      searchOption: {
        city: '石家庄',
        citylimit: false,
      },
      mapCenter: [114.512417, 38.061424],
      address: '',
      events: {
        click(e) {
          const { lng, lat } = e.lnglat;
          self.lng = lng.toFixed(6);
          self.lat = lat.toFixed(6);
          console.log(lng, lat);
        },
      },
    };
  },
  created() {
  },
  methods: {
    mapConfirm(state) {
      this.$emit(
        'map-confirm',
        { state: state, location: this.lng + ', ' + this.lat },
      );
    },
    onSearchResult(pois) {
      var latSum = 0;
      var lngSum = 0;
      if (pois.length > 0) {
        pois.forEach(poi => {
          const { lng, lat } = poi;
          lngSum += lng;
          latSum += lat;
          this.markers.push([poi.lng, poi.lat]);
        });
        const center = {
          lng: lngSum / pois.length,
          lat: latSum / pois.length,
        };
        this.mapCenter = [center.lng, center.lat];
        this.lng = center.lng.toFixed(6);
        this.lat = center.lat.toFixed(6);
      }
    },
  },
};
</script>

<style>
.amap-demo {
  height: 90vh !important;
}
.search-box {
  position: absolute;
  top: 60px;
  left: 30%;
}
.amap-page-container {
  position: relative;
  top: -45px;
}
.toolbar {
  padding: 20px;
}
</style>
