map-control.js 1.9 KB
Newer Older
DCloud-WZF's avatar
DCloud-WZF 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
import getRealPath from 'uni-platform/helpers/get-real-path'

export default {
  props: {
    id: {
      type: [Number, String],
      default: ''
    },
    position: {
      type: Object,
      require: true
    },
    iconPath: {
      type: String,
      require: true
    },
    clickable: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      control: null
    }
  },
  watch: {
    props: function () {
      this.updateControl()
    }
  },
  mounted () {
    this.$parent.mapReady(() => {
      this.addControl()
    })
  },
  beforeDestroy () {
    this.removeControl()
  },
  methods: {
    addControl () {
      this.control = document.createElement('div')
      const style = this.control.style
      style.position = 'absolute'
      style.width = 0
      style.height = 0
      style.top = 0
      style.left = 0
      style.zIndex = 999
      const img = new Image()
      img.src = getRealPath(this.iconPath)
      img.onload = () => {
        if (this.position.width) {
          img.width = this.position.width
        }
        if (this.position.height) {
          img.height = this.position.height
        }
        const style = img.style
        style.position = 'absolute'
        style.left = (this.position.left || 0) + 'px'
        style.top = (this.position.top || 0) + 'px'
        style.maxWidth = 'initial'

        this.control.appendChild(img)
        this.$parent.$el.appendChild(this.control)
      }
      img.onclick = ($event) => {
        if (this.clickable) {
          this.$parent.$trigger('controltap', $event, {
            controlId: this.id
          })
        }
        $event.stopPropagation()
      }
    },
    updateControl () {
      this.removeControl()
      this.addControl()
    },
    removeControl () {
      if (this.control) {
        this.control.remove()
      }
    }
  },
  render () {
    return null
  }
}