<template>
  <div id="allmap" :style="mapStyle">
  </div>
</template>

<script>
import Vue from 'vue'

export default {
  title: '百度地图组件',
  props: ['offset', 'markers'],
  data() {
    return {
      mapStyle: {
        width: this.$root.$el.clientWidth + 'px',
        height: (this.$root.$el.clientHeight - this.offset) + 'px'
      }
    }
  },
  methods: {
    mapCallback () {
      console.log('called back')
      window.map = new BMap.Map("allmap")
      Vue.mapLoaded = true
      this.render()
    },
    patch () {
      let a = document.getElementById('allmap').getElementsByClassName('BMap_cpyCtrl BMap_noprint anchorBL')
      if(a.length != 0) {
        a[0].style.height = 'auto'
      } else {
        window.setTimeout(this.patch, 500)
      }
    },
    render () {
      // 百度地图API功能
      window.map.clearOverlays();
      console.log('djdkdkdkd' + this.markers.length)
      if(this.markers.length == 0)
        window.map.centerAndZoom(new BMap.Point(116.404, 39.915), 11)
      else
        window.map.centerAndZoom(new BMap.Point(this.markers[0].longitude, this.markers[0].latitude), 11)
      window.map.addControl(new BMap.NavigationControl())
      this.markers.forEach(function(pos) {
        var point = new BMap.Point(pos.longitude,pos.latitude);
      	var marker = new BMap.Marker(point);  // 创建标注
      	window.map.addOverlay(marker);              // 将标注添加到地图中
      	var infoWindow = new BMap.InfoWindow(pos.hint);  // 创建信息窗口对象
      	marker.addEventListener("click", function(){
      		window.map.openInfoWindow(infoWindow,point); //开启信息窗口
      	});
      })
      this.patch()
    }
  },
  ready () {
      console.log('a map ready')
      if(Vue.mapLoaded) {
        window.map = new BMap.Map("allmap")
        this.render()
      } else {
        window.__mapCallback__ = this.mapCallback
        let element = document.createElement('script')
        element.setAttribute("type","text/javascript")
        element.setAttribute("src", 'http://api.map.baidu.com/api?v=2.0&ak=CAErfbr2DatVA6rHdoUELPynrdPh9A6S&callback=__mapCallback__')
        document.body.appendChild(element)
      }
  }
}
</script>
