<template>
  <div class="amap-page-container">
    <el-amap-search-box class="search-box" style="top:52px" :search-option="searchOption" :on-search-result="onSearchResult"></el-amap-search-box>
    <el-amap vid="amapDemo" :center="mapCenter" :zoom="zoom" class="amap-demo" :events="events">
      <el-amap-marker v-for="marker in markers" :key="marker.id" :position="marker"></el-amap-marker>
    </el-amap>
    <div class="toolbar">
      position: {{ lng }}, {{ lat }}
    </div>
  </div>
</template>
<script>
import Vue from 'vue';
import VueAMap from 'vue-amap';
Vue.use(VueAMap);
VueAMap.initAMapApiLoader({
  key: '2719fe261fee06a08dcb4980990879da',
  plugin: ['AMap.Geocoder'],
  v: '1.4.4',
  uiVersion: '1.0.11',
});
export default {
  data() {
    return {
      lng: 0,
      lat: 0,
      zoom: 13,
      center: [114.512417, 38.061424],
      markers: [
        [121.59996, 31.197646],
        [121.40018, 31.197622],
        [121.69991, 31.207649],
      ],
      searchOption: {
        city: '上海',
        citylimit: true,
      },
      mapCenter: [114.512417, 38.061424],
      address: '',
      events: {
        click(e) {
          const self = this;
          const { lng, lat } = e.lnglat;
          self.lng = lng;
          self.lat = lat;
          // var geocoder = VueAMap.Geocoder({
          //   radius: 1000,
          //   extensions: 'all',
          // });
          // geocoder.getAddress([lng, lat], function(status, result) {
          //   if (status === 'complete' && result.info === 'OK') {
          //     if (result && result.regeocode) {
          //       self.address = result.regeocode.formattedAddress;
          //       self.$nextTick();
          //     }
          //   }
          // });
        },
      },
    };
  },
  created() {
  },
  methods: {
    addMarker() {
      const lng = 121.5 + Math.round(Math.random() * 1000) / 10000;
      const lat = 31.197646 + Math.round(Math.random() * 500) / 10000;
      this.markers.push([lng, 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;
        this.lat = center.lat;
      }
    },
  },
};
</script>

<style>
.amap-demo {
  height: 600px !important;
}
.search-box {
  position: absolute;
  top: 25px;
  left: 20px;
}
.amap-page-container {
  position: relative;
}
</style>
