selectMapPos.vue 2.96 KB
<template>
  <div class="select-map-pos-container">
    <div id="selectMap" class="map-view"></div>
    <div class="map-hint">点击地图选择位置,经纬度将自动填充</div>
  </div>
</template>

<script>
import { getCommunityId } from '@/api/community/communityApi'

export default {
  name: 'SelectMapPos',
  props: {
    elementId: {
      type: String,
      default: 'selectMap'
    },
    initData: {
      type: Object,
      default: () => ({})
    }
  },

  data() {
    return {
      map: null,
      marker: null,
      communityId: ''
    }
  },
  mounted() {
    this.communityId = getCommunityId()
  },
  methods: {
    initMap(_data) {
      let _lng = 116.397128
      let _lat = 39.916527

      if (_data.lng) _lng = _data.lng
      if (_data.lat) _lat = _data.lat

      if (this.map) {
        this.map.destroy()
        this.map = null
      }
      this.marker = null

      const map = new window.AMap.Map('selectMap', {
        center: [_lng, _lat],
        zoom: 13,
        resizeEnable: true
      })

      const _this = this

      map.on('click', function (ev) {
        const lng = ev.lnglat.getLng()
        const lat = ev.lnglat.getLat()

        _this.$emit('position-change', { lat, lng })

        if (!_this.marker) {
          _this.marker = new window.AMap.Marker({
            position: [lng, lat],
            map: map,
            icon: new window.AMap.Icon({
              size: new window.AMap.Size(25, 35),
              imageSize: new window.AMap.Size(25, 35),
              image: '/img/maper.png'
            })
          })
        } else {
          _this.marker.setPosition([lng, lat])
        }
      })

      this.map = map

      // 如果传入了已有坐标,在地图上显示标记
      if (_data.lng && _data.lat) {
        this.marker = new window.AMap.Marker({
          map: this.map,
          position: [_lng, _lat],
          icon: new window.AMap.Icon({
            size: new window.AMap.Size(25, 35),
            imageSize: new window.AMap.Size(25, 35),
            image: '/img/maper.png'
          })
        })
      }
    },

    addMarker(position) {
      if (this.marker) {
        this.marker.setMap(null)
        this.marker = null
      }

      this.marker = new window.AMap.Marker({
        map: this.map,
        position: position,
        icon: new window.AMap.Icon({
          size: new window.AMap.Size(25, 35),
          imageSize: new window.AMap.Size(25, 35),
          image: '/img/maper.png'
        })
      })

      this.map.setCenter(position)
      this.map.setZoom(16)
    },

    updatePosition(lat, lng) {
      if (!this.map) return
      this.addMarker([lng, lat])
    }
  },
  beforeDestroy() {
    if (this.map) {
      this.map.destroy()
      this.map = null
    }
  }
}
</script>

<style scoped>
.select-map-pos-container {
  width: 100%;
}
.map-view {
  width: 100%;
  height: 400px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
.map-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 6px;
}
</style>