<template>
  <div id="mapComp" class="mapComp" />
  <input id="pickerInput" type="text" placeholder="输入关键字选取地点">

</template>

<script setup name="mapComp">
import GMap from '@/utils/map/GMap'
import { nextTick } from 'vue'

const emit = defineEmits(['mapEmit'])
let marker = null

nextTick(() => {
  GMap.then((AMap) => {
    const map = new AMap.Map('mapComp', {
      zoom: 13,
      center: [118.773319, 31.828123]
    })

    // 添加缩放工具
    const toolbar = new AMap.ToolBar()
    map.addControl(toolbar)

    // 搜索
    AMapUI.loadUI(['misc/PoiPicker'], function(PoiPicker) {
      const poiPicker = new PoiPicker({
        input: 'pickerInput'
      })

      poiPicker.on('poiPicked', ({ item }) => {
        const inp = document.getElementById('pickerInput')
        inp.value = item.name
        // map.setCenter(item.location) // 移动到中心位置
        if (marker) map.remove(marker)
        marker = new AMap.Marker({
          title: item.address,
          icon: '//vdata.amap.com/icons/b18/1/2.png'
        })

        marker.setMap(map)
        marker.setPosition(item.location)
        map.setCenter(item.location)

        emit('mapEmit', item.location)
      })
    })
    map.on('click', ({ lnglat }) => {
      if (marker) map.remove(marker) // 只取一次maker点
      marker = new AMap.Marker({
        position: new AMap.LngLat(lnglat.lng, lnglat.lat),
        offset: new AMap.Pixel(-10, -10),
        icon: '//vdata.amap.com/icons/b18/1/2.png'
      })
      map.add(marker)
      emit('mapEmit', lnglat)
    })
  }).catch(e => console.log(e))
})

</script>

<style lang="scss" scoped>
.mapComp {
  width: 100%;
  height: 400px;
}

#pickerInput {
  position: absolute;
  z-index: 9999;
  top: 30px;
  left: 30px;
  width: 200px;
  padding: 5px 5px;
}

.amap_lib_placeSearch .poibox.highlight {
  background-color: #CAE1FF;
}

.amap_lib_placeSearch .poi-more {
  display: none !important;
}
</style>
