<template>
<div>
  <div v-if="!hasBmView" ref="view" style="width: 100%; height: 100%">
  </div>
  <slot></slot><!--此处的插槽放置地下的功能控件按钮-->
</div>
</template>
<script>
import Vue from 'vue'
import 'ol/ol.css'
import {Map} from 'ol'
import View from 'ol/View'
import config from './mapConfig'
import VectorLayer from 'ol/layer/Vector'
import VectorSource from 'ol/source/Vector'
import Feature from 'ol/Feature'
import { Select,Translate } from 'ol/interaction'
import Point from 'ol/geom/Point'
import {fromLonLat} from 'ol/proj'
import {
        Fill,
        Stroke,
        Style,
        Text,
        Icon,
        Circle
    } from 'ol/style'
import Cluster from 'ol/source/Cluster'
import { getFeatureOfMaxZIndex } from '../base/util'
import { GeometryType } from '../base/GeometryType'
import $ from 'jquery'
import  FullScreen  from '../controls/FullScreen'
import  Loading  from '../controls/Loading'
import {defaults as defaultControls} from 'ol/control'
import {defaults as defaultInteractions, DragRotateAndZoom,DragPan} from 'ol/interaction'
// import {DragPan} from 'ol/interaction'
import axios from 'axios'
import qs from 'qs'
import Overlay from 'ol/Overlay'
import {clearSpatial,addVector} from '../base/poiQuery'
import  Overview  from '../controls/Overview'
import  CanvasScaleLine  from '../controls/CanvasScaleLine'
import  ZoomSlider  from '../controls/ZoomSlider'
// import {PanZoomBar} from 'ol/control'
// import {ol} from 'ol';
const _panFactor = 0.0005
var newMarker;
export default {
  name: 'sl-map',
  props: {
    mapType: {
      type: String
    },
    center: {
      type: Array,
      required: true
    },
    zoom: {
      type: Number,
      default: 2
    },
    minZoom: {
      type: Number,
      default: 0
    },
    maxZoom: {
      type: Number,
      default: 28
    },
    extent: {
      type: Array,
      default: function () {
        return []
      }
    },
    projection: {
      type: String,
      default: 'EPSG:3857'
    },
    rotation: {
      type: Number,
      default: 0
    },
    extentFlag:{
      type:Boolean,
      default:true
    },
    resolution:{
      type:Array
    },
    isOpenScaleLine:{
      type:Boolean,
      default:true
    },
    isOpenZoomSlider:{
      type:Boolean,
      default:true
    },
    isOpenOverview:{
      type:Boolean,
      default:true
    },
    isOpenFullScreen:{
      type:Boolean,
      default:true
    }
  },
  data () {
    return {
      hasBmView: false,
      olmap: null,
      // movingFlag:false
    }
  },
  watch: {
   mapType: function(type) {
      var layers = this.getAllLayers()
      layers.forEach((layer) => {
        let flag = layer.get('isBaseMap')
        if(flag) {//如果是baseMap为ture则删除
           this.olmap.removeLayer(layer)
        }
      })
      if(config.layers(type)){
        this.olmap.addLayer(config.layers(type))
      }  
   },
   mounted(){

   },
   // 监听地图中心点---
   center (val) {
      const { olmap, center } = this
      olmap.getView().setCenter(center)
    },
    // 监听地图缩放级别----
    zoom (val) {
      const { olmap } = this
      olmap.getView().setZoom(val)
    },
    // 监听地图最新缩放级别
    minZoom (val) {
      const { olmap } = this
      olmap.getView().setMinZoom(val)
    },
    // 监听地图最大缩放级别
    maxZoom (val) {
      const { olmap } = this
      olmap.getView().setMaxZoom(val)
    },
    // 监听地图范围变化-----
    extent(mapExtent) {
      this.olmap.getView().fit(mapExtent)
    }
  },
  methods: {
    initMap() {
      let $el = this.$refs.view // 地图布局，地图是用容器渲染-------
      for (let $node of this.$slots.default || []) {
        if ($node.componentOptions && $node.componentOptions.tag === 'sl-view') {
          this.hasBmView = true
          $el = $node.elm
        }
      }
      const { zoom, center, minZoom, maxZoom, projection, mapType,resolution} = this
      var { extent} = this
      if (extent && extent.length === 0) {
        extent = undefined
      }
      // let EPSG3857 = fromLonLat(center);
      var view = new View({//初始化时候的视角范围
        projection,
        center,
        zoom,
        minZoom,
        maxZoom,
      })
      const map = new Map({
        target: $el,
        keyboardEventTarget:document,
        view,
        controls: defaultControls({attribution:false, zoom: false}),
        interactions: defaultInteractions().extend([
          new DragRotateAndZoom()
        ])
      })
      let layer = null
      if(config.layers(mapType)){
         layer = config.layers(mapType)
      }
      if (layer) {
        map.addLayer(layer)
       // 添加鹰眼缩略图控件----
        // var ov = new Overview(
        //   {	layers: [layer],
        //     minZoom,
        //     maxZoom,
        //     zoom,
        //     center,
        //     projection
        //   })
        //   map.addControl(ov)
        // this.isOpenOverview?map.addControl(ov):map.removeControl(ov)
      }

      // 添加比例尺控件
      var scaleLineControl = new CanvasScaleLine()
      this.isOpenScaleLine?map.addControl(scaleLineControl):map.removeControl(scaleLineControl)
      //添加zoom控件
      this.isOpenZoomSlider?map.addControl(new ZoomSlider()):map.removeControl(new ZoomSlider())
      //地图全屏控件
      this.isOpenFullScreen?map.addControl(new FullScreen()):map.removeControl(new FullScreen())
      this.olmap = map
      Vue.prototype.$map = map
      this.$emit('ready', {
        map
      })
      // 地图移动结束事件--根据屏幕范围进行查询
      this.olmap.on('moveend', ev => {
        let zoom = this.olmap.getView().getZoom()
        //  if(zoom >= 18){
        //     console.log("触发获取当前屏幕视域范围查询数据库")
        //     let currentExtent = this.getCurrentExtent();
        //     let config =  {
        //       "id":'poiExtent',
        //       "scale":0.9,
        //       "zIndex":10,
        //       "serurl":'http://172.20.36.63:7001/ExtentPoi',
        //       "tableName":"qingpupoi",
        //       "img":'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABMAAAAfCAYAAAAFkva3AAACd0lEQVR42qWU3UuTYRjG34iiw+gk6CAp2XRqsyazWRuz8c656UF/QV8URhQSNaMP5kzRudQ5Zy3zD+i0gygiZ44oogjDJJBqjMTS1Gxzm1s17+4rYmBzbXt38OPhue/r+jEG7yMQURoWZ2QHY2XGmBkm8ff0Y479er01F3N3eBPTzsQs7gQ1eJPUOETUOMzwiTvm2COH/LqyekdoK+Mz98ep4Q4XhzODPXKcH2W2rZGZupY2MiP17hWycDBXkOfec2ZzSlbXuWg39UXJPER5gx76BJmxY347EzPx/1HHy3xBD314BLF97qLYs0zG26uSQZ89VsHQ9mVUHFgh0ZuUDPrwCIfsM3OGmz/I4P0lGfTZMyvU2qaTtbd+UqHAI+ivBZf1gwnSs10q6LMnLOiuBsZ1rgjpeCCZ/gix542gvfLerXXM00FPXDJaxwKxxyMcuDSlqbEFSeNZkQz68Pz5Ampa3o3t75yl6oFY3qCHfupz0lgnS5i42hUmtTuaM8ijh35KBqovTLSp7Z+oqj+aM8ijl/YEqc+Pb2ECqq6vtM8VyQpyyKOXJgNVza8Pqy5PkbJvOSvIIZ/xpQWqcy9HKvnnV/SGM4I953zI/1e29+wLJZMs7w1RJrBHLqsMVJ55drfCFiBFz/c0MMceuZxkytNPy5hV+Y0l+hfMsc9ZBvY0+e+VtgZJ5vyWAnfMsc9LVn7qiahofkXFzsUUuGOet6zspG8D87G44zPt7l4gnLhjnrcMKE48tsmsb6mIXwWcfG/FXJKs9PijUnmTn3byE4UTd8kyUHLs4Yei69OEE/eCZPKjDwZ3tUwSzoJlsiP3RSbEGLNlfwPf80fNP6DL+QAAAABJRU5ErkJggg==',
        //     }
        //     var initData = {
        //       "posArray": [{
        //             "extent":currentExtent,
        //             "tableName": config.tableName
        //         }]
        //     }
        //     axios.post(config.serurl, qs.stringify(initData), {
        //         headers: {
        //             'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        //     }
        //   }).then(res => {
        //       let data = res.data
        //       clearSpatial('poiExtent',map)
        //       clearSpatial('poi',map)
        //       addVector(data,map,config);
        //   })
        //   }else{
        //       console.log("正常显示")
        //       clearSpatial('poiExtent',map)
        //       let domArr = document.getElementsByClassName("popup");
        //       if(domArr!=undefined||domArr!=null){
        //           for(var i = 0;i<domArr.length;i++){
        //               if(domArr[i].innerHTML.indexOf("地址")>-1){
        //                   domArr[i].style.display="none"
        //               }
        //           }
        //       }
        //   }
        let center = this.olmap.getView().getCenter()
        let extent = this.olmap.getView().calculateExtent(this.olmap.getSize())
        this.$emit('zoomMoveEnd', { zoom, center, extent })
      })
      // 地图开始移动事件
      this.olmap.on('movestart', ev => {
      })
      // 鼠标拖拽事件
      this.olmap.on('pointerdrag', ev => {
          let loc = ev.coordinate
          this.$emit('mousedrag', { lon: loc[0], lat: loc[1] });
          
          this.olmap.handleResize_();//重新渲染地图
          this.olmap.handleViewChanged_();
          this.olmap.handleViewPropertyChanged_();
          // this.olmap.render();
      })
      // 鼠标移动事件
      this.olmap.on('pointermove', ev => {
        let loc = ev.coordinate
        let featurelist = []
        let obj = null
        this.forEachFeatureAtPixel(ev.pixel, (fea, layer) => {
          if (layer) {
            let zIndex = layer.getZIndex()
            let id = layer.get("id")         
            if(id) {
              fea.set("layerId", id)
            }
            featurelist.push({index: zIndex, feature: fea})
          }
        })
        let vector = getFeatureOfMaxZIndex(featurelist)
        let feature = null 
        if (vector) {
          map.getTargetElement().style.cursor = 'pointer'
          let flag = vector.get('features')
          if (flag) { // 表示该要素是聚合要素-------
               // 获取该聚合要素类含有的要素的个数----
              var size = vector.get('features').length
              if (size === 1) { 
                  feature = vector.get('features')[0]
              } else {
                  feature = null
              }
          } else { 
               feature = vector  
          }  
        } else {
          map.getTargetElement().style.cursor = '-webkit-grab'
        }
        if (feature) {   
            obj = {
              lon: loc[0],
              lat: loc[1],
              feature,
              attributes: feature.get('attributes'),
              pixel:ev.pixel,
              featurelist
            }
        } else {
            obj = {
              lon: loc[0],
              lat: loc[1],
              pixel:ev.pixel
            }
        }
        obj.dragging = ev.dragging
        this.$emit('mousemove', obj)
      })
      // 鼠标单击事件
      this.olmap.on('click', ev => {
        let loc = ev.coordinate
         //获取单选按钮的选项
        var type = $('input[name="label"]:checked').val();
        //获取位置坐标
        // var point = evt.coordinate;
        //如果类型是矢量标注则添加矢量标签，否则添加覆盖标签
        if (type == 'vector') {
            this.addVectorLabel(loc);
            return;
        }
        let featurelist = []
        let center = []
        let obj = null
        this.forEachFeatureAtPixel(ev.pixel, (fea, layer) => {
          if (layer) {
            let zIndex = layer && layer.getZIndex()
            featurelist.push({index: zIndex, feature: fea})
          }
        })
        let vector = getFeatureOfMaxZIndex(featurelist)
        let feature = null
        if (vector) {
          let flag = vector.get('features')
          if (flag) { // 表示该要素是聚合要素-------
               // 获取该聚合要素类含有的要素的个数----
              var size = vector.get('features').length
              if (size === 1) { 
                  feature = vector.get('features')[0]
              } else {
                  feature = null
              }
          } else { 
               feature = vector  
          }  
        } 
        // 判断要素是否拾取到-------
        if (feature) {
            let type = feature.getGeometry().getType()
            if (type === GeometryType.POINT) {
              center = feature.getGeometry().getCoordinates()
            }
            if (type === GeometryType.POLYGON) {
              center = feature.getGeometry().getInteriorPoint().getCoordinates()
            }
            if (type === GeometryType.MULTIPOLYGON) {
              const bounds = feature.getGeometry().getExtent()
              center = [(bounds[0] + bounds[2]) / 2, (bounds[1] + bounds[3]) / 2]
            }
            if (type === GeometryType.POLYLINE) {
              center = feature.getGeometry().getLastCoordinate()
            }
            obj = {
              lon: loc[0],
              lat: loc[1],
              feature,
              attributes: feature.get('attributes'),
              type: type,
              center: center,
              pixel:ev.pixel,
              featurelist
            }
        } else {
          obj = {
            lon: loc[0],
            lat: loc[1],
            pixel:ev.pixel
          }
        }
        this.$emit('click', obj)
      })
      // 鼠标单次单击事件
      this.olmap.on('singleclick', ev => {
        let loc = ev.coordinate
        this.$emit('singleclick', { lon: loc[0], lat: loc[1] })
      })
      this.olmap.on('mouseover', ev => {
        let loc = ev.coordinate
        // this.$emit('mouseover', { lon: loc[0], lat: loc[1] })
      })
      //鼠标右键事件
      this.olmap.on('contextmenu', ev => {
        let loc = ev.coordinate
        this.$emit('rightClick', { lon: loc[0], lat: loc[1] })
         ev.preventDefault();
      })
      // 鼠标双击事件
      this.olmap.on('dblclick', ev => {
        let loc = ev.coordinate
        this.$emit('dblclick', { lon: loc[0], lat: loc[1] })
      })
      // 地图渲染事件----渲染前 准备渲染，未渲染
      this.olmap.on('precompose', ev => {
        this.$emit('precompose')
        // console.log('地图渲染前------地图渲染事件')
      })
      // 地图渲染事件----渲染后  地图渲染中
      this.olmap.on('postcompose', ev => {
        this.$emit('postcompose', ev)
        // console.log('地图渲染后------地图渲染事件')
      })
      // 地图事件，渲染后----  渲染全部结束
      this.olmap.on('postrender', ev => {
        this.$emit('postrender')
        // console.log('地图渲染后------地图事件')
      })
      // 地图事件，渲染后----
      this.olmap.on('change:layerGroup', ev => {
        // console.log('地图事件---图层发生变化----')
      })
      // // 地图事件，渲染后----
      // this.olmap.on('change:view', ev => {
      //   console.log('地图视图发生改变-----')
      //   // console.log(ev)
      // })
      // 地图缩放事件
      this.olmap.getView().on('change:resolution', ev => {
        let zoom = this.olmap.getView().getZoom()
        let center = this.olmap.getView().getCenter()
        let extent = this.olmap.getView().calculateExtent(this.olmap.getSize())
        this.$emit('zoomend', { zoom, center, extent })
        // console.log('地图缩放级别改变导致地图范围改变了')
        // console.log(extent + '范围')
        // console.log(center + '中心点')
      })
    },
    // 定位缩放地图-----
    centerAndZoom (x, y, level) {
      this.centerAt(x, y)
      this.setLevel(level)
    },
    // 定位地图-----
    centerAt (x, y) {
      this.olmap.getView().setCenter([x, y])
    },
    // 根据偏差定位地图-----
    centerAtWithOffset (x, y, offX, offY) {
      var _screenP = this.toScreen(x, y)
      _screenP.x = _screenP.x + offX
      _screenP.y = _screenP.y + offY
      var _mapP = this.toMap(_screenP.x, _screenP.y)
      this.centerAt(_mapP.x, _mapP.y)
    },
    // 设置地图缩放级别---
    setLevel (level) {
      this.olmap.getView().setZoom(level)
    },
    // 向左移动地图-----
    moveToLeft () {
      var view = this.olmap.getView()
      var mapCenter = view.getCenter()
      // 让地图中心的x值增加，即可使得地图向左移动，增加的值根据效果可自由设定
      mapCenter[0] += _panFactor
      view.setCenter(mapCenter)
      this.olmap.render()
    },
    // 向右移动地图-----
    moveToRight () {
      var view = this.olmap.getView()
      var mapCenter = view.getCenter()
      // 让地图中心的x值减少，即可使得地图向右移动，减少的值根据效果可自由设定
      mapCenter[0] -= _panFactor
      view.setCenter(mapCenter)
      this.olmap.render()
    },
    // 向上移动地图
    moveToUp () {
      var view = this.olmap.getView()
      var mapCenter = view.getCenter()
      // 让地图中心的y值减少，即可使得地图向上移动，减少的值根据效果可自由设定
      mapCenter[1] -= _panFactor
      view.setCenter(mapCenter)
      this.olmap.render()
    },
    // 向下移动地图
    moveToDown () {
      var view = this.olmap.getView()
      var mapCenter = view.getCenter()
      // 让地图中心的y值增加，即可使得地图向下移动，增加的值根据效果可自由设定
      mapCenter[1] += _panFactor
      view.setCenter(mapCenter)
      this.olmap.render()
    },
    // 获取当前地图的中心点------
    getCurrCenter () {
      return this.olmap.getView().getCenter()
    },
    // 地图级别
    getLevel () {
      return this.olmap.getView().getZoom()
    },
    // 设置地图范围
    setExtent (extent) {
      this.olmap.getView().fit([extent.minX, extent.minY, extent.maxX, extent.maxY], this.olmap.getSize())
    },
    // 获取地图当前范围------
    getCurrentExtent () {
      var extent = this.olmap.getView().calculateExtent(this.olmap.getSize())
      if (!extent) {
        return null
      }
      return {
        minX: extent[0],
        minY: extent[1],
        maxX: extent[2],
        maxY: extent[3]
      }
    },
    // 根据事件获取事件发生的位置----
    getEventCoordinate (event) {
      return this.olmap.getEventCoordinate(event)
    },
    /*iconfont以dom形式添加并且可以移动——罗旭*/
    addOverlayLabelGJ(id,map,coordinate,element,offset) {//桔弓科技添加iconfont并可移动
        //新建一个覆盖层
        var newMarker = new Overlay({
            id:id,
            //设置位置为当前鼠标点击的坐标
            position: coordinate,
            //设置覆盖层与位置之间的匹配方式
            // positioning: 'center-center',//如果包含center这块可能是openlayers的一个bug数据量大了就卡
            positioning:'top-left',
            //覆盖层元素
            element: element,
            //事件传播到地图视点的时候是否应该停止
            // stopEvent: false
        });
        //将覆盖层添加到map中
        this.olmap.addOverlay(newMarker);
        var _this = this;
        // display popup on click
          var dragPan = null;
          map.getInteractions().forEach(function(interaction){
            if (interaction instanceof DragPan) {
              dragPan = interaction;  
            }
          });
          //这个不像其他的事件，放置了鼠标后有end事件可以重新设置true或false
          element.addEventListener('click', function(evt) {//当鼠标按钮被按下执行
            // _this.movingFlag = true;//开始移动
            dragPan.setActive(false);
            newMarker.set('dragging', true);
            console.info('start dragging');
          });
          element.addEventListener('contextmenu', function(evt) {//当鼠标按钮被按下执行
            if (newMarker.get('dragging') === true) {
                console.info('stop dragging');
                dragPan.setActive(true);
                newMarker.set('dragging', false);
                console.log("endPos====",newMarker.values_.position)
                _this.$emit('contextmenuPos',newMarker.values_.position)
              }
          });
          map.on('pointermove', function(evt) {//鼠标移动事件
            // var startPoint=iconFeature.getGeometry().getCoordinates();
              if (newMarker.get('dragging')) {
                var dd2=map.getPixelFromCoordinate(evt.coordinate);
                // var newX=dd2[0]-0;//减去偏移量
                // var newY=dd2[1]-(-50);
                var newX=dd2[0]-0;//减去偏移量
                var newY=dd2[1]-(0);
                var newPoint=map.getCoordinateFromPixel([newX,newY]);
                console.log(newPoint+"+++++++++++=");
                newMarker.setPosition(newPoint);
                console.log("鼠标移动事件")
                // _this.movingFlag = false;//移动结束
              }
          });
          // map.on('contextmenu', function(evt) {//如果想要在释放指针时触发一个事件,那么就需要使用pointerup,在桔弓这块不起作用，故用map中的rightClick方法
          //     console.log("kkkkkk-鼠标右键事件")
          //     console.log(newMarker)
          //     console.log(newMarker.get('dragging'))
          //     if (newMarker.get('dragging') === true) {
          //       console.info('stop dragging');
          //       dragPan.setActive(true);
          //       newMarker.set('dragging', false);
          //       var dd2=map.getPixelFromCoordinate(evt.coordinate);
          //       var newX=dd2[0]-0;//减去偏移量
          //       var newY=dd2[1]-(0);
          //       var newPoint=map.getCoordinateFromPixel([newX,newY]);
          //       console.log("endPos====",newPoint)
          //       _this.$emit('contextmenuPos', newPoint)
          //     }
          // });
    },
    /*添加Feature矢量标签并且可以以select的方式移动——罗旭*/
    addVectorLabelJG(map,markerObj,offset) {//添加矢量标签
          //初始化一个新的点要素
          var newFeature = new Feature({//features中可以放attributes
              geometry: new Point([markerObj.lon,markerObj.lat]),
              name: markerObj.name,
              attributes:markerObj
          });
          //设置点的样式
          newFeature.setStyle(this.createLabelStyle(newFeature,markerObj.imgSrc,markerObj.scale,offset,markerObj.fontStyle));//这块添加图片
          //初始化矢量数据源
          var vectorSource = new VectorSource({
              //指定要素
              features: [newFeature]
          });
          //初始化矢量图层
          var vectorLayer = new VectorLayer({
              //数据源
              id:markerObj.vectorId,
              source: vectorSource
          });
          // let tips = new Overlay({
          //     id:markerObj.tipsJG,
          //     element: dom,
          //     offset: offset,//[12, -40]
          //     positioning: 'center-center'
          // })
          // let closeFeature = tips.getSource().getClosestFeatureToCoordinate(point)
          // tips.setPosition([markerObj.lon,markerObj.lat])
          // this.olmap.addOverlay(tips);
          //将矢量图层添加到map中
          this.olmap.addLayer(vectorLayer);
          vectorLayer.setZIndex(markerObj.z_index)
          //拖拽
          //clearInteraction(this.olmap)
          var select = new Select({
             id:"slectMarker",
             layers:[vectorLayer],
          });//选择图形interaction
          this.olmap.addInteraction(select);//不可能每次进来一次添加一次
          var translate = new Translate({//拖拽移动interaction
              id:"translateMarker",
              features: select.getFeatures(),//拖拽的为选择的要素
              hitTolerance:0,
          });
          this.olmap.addInteraction(translate);//不可能每次进来一次添加一次
          var _this = this;
          translate.on('translateend',function(f){
              //  _this.$emit('endPos', carType + "_" + _this.countTwo)
              _this.$emit('moveEndPos', f.coordinate)
              console.log("ooooooooooooooooo");//拖拽完成事件，可以获取拖拽后的要素
          });
          // var initData = {
          //     "posArray": [
          //       markerObj
          //   ]
          // }
          // axios.post('http://172.20.36.63:7001/findMarker', qs.stringify(initData), {//点击之后就添加到后端数据库
          //     headers: {
          //         'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
          //     }
          //     }).then(res => {
          //       console.log("************")
          // })
    },
    //添加矢量标签
    addVectorLabel(coordinate) {
          let markerObj = {
                lon: coordinate[0],
                lat: coordinate[1],
                type: 'markerType',
                name : "地图标注",
                id:"markerFlag"
          }
          //初始化一个新的点要素
          var newFeature = new Feature({//features中可以放attributes
              geometry: new Point(coordinate),
              name: '标注点',
              attributes:markerObj
          });
          //设置点的样式
          newFeature.setStyle(this.createLabelStyle(newFeature));//这块添加图片
          //初始化矢量数据源
          var vectorSource = new VectorSource({
              //指定要素
              features: [newFeature]
          });
          //初始化矢量图层
          var vectorLayer = new VectorLayer({
              //数据源
              id:"markerFlag",
              source: vectorSource
          });
          const contaner = document.createElement('div')
          const a = document.createElement('a')
          a.style.border = '1px solid rgb(255, 1, 3)'
          a.style.background = '#ffffff'
          a.style.width = '15px'
          a.style.height = '18px'
          a.style.marginLeft = '5px'
          a.style.marginRight = '3px'
          a.style.cursor = 'hand'
          a.innerHTML = '✖'
          contaner.appendChild(a)
          let tips = new Overlay({
            id:'tips',
            element: contaner,
            offset: [12, -40],
            positioning: 'center-center'
          })
          // let closeFeature = tips.getSource().getClosestFeatureToCoordinate(point)
          tips.setPosition([coordinate[0],coordinate[1]])
          // this.olmap.addOverlay(tips);
          //将矢量图层添加到map中
          this.olmap.addLayer(vectorLayer);
          //拖拽
          //clearInteraction(this.olmap)
          var select = new Select({
             id:"slectMarker",
             layers:[vectorLayer],
          });//选择图形interaction
          this.olmap.addInteraction(select);//不可能每次进来一次添加一次
          var translate = new Translate({//拖拽移动interaction
              id:"translateMarker",
              features: select.getFeatures(),//拖拽的为选择的要素
              hitTolerance:0,
          });
          this.olmap.addInteraction(translate);//不可能每次进来一次添加一次
          var _this = this;
          translate.on('translateend',function(f){
              _this.$emit('moveEndPos', f.coordinate)
              console.log("ooooooooooooooooo");//拖拽完成事件，可以获取拖拽后的要素
          });
          //将矢量图标添加到地图之后提交到后端nodejs
          //this.$emit('returnMarkerFlag', markerObj)//这块用不用给前端返回暂时先待定
          // var attr = obj.feature.values_.attributes
          //获取到地图标记图标后的点击图标属性信息
          var initData = {
              "posArray": [
                markerObj
            ]
          }
          axios.post('http://172.20.36.63:7001/findMarker', qs.stringify(initData), {//点击之后就添加到后端数据库
              headers: {
                  'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
              }
              }).then(res => {
                console.log("************")
          })
    },
    //添加文字标注
    addOverlayLabelText(idText,ele,map,number,coordinate,offset) {
        //创建一个div元素
        // var elementDiv = document.createElement('div');
        // //设置div元素的样式类
        // elementDiv.className = 'marker';
        //设置div元素的title属性
        // elementDiv.title = number;
         ele.title = number;
        // //获取id为label的div标签
        // var overlay = document.getElementById('label');
        // //将新创建的div标签添加到overlay中
        // overlay.appendChild(ele);
        //创建一个a标签元素
        var elementA = document.createElement('a');
        //设置a标签的样式类
        elementA.className = 'addressOverlay';
        //设置a标签的链接地址
        // elementA.href = '#';
        //设置a标签的超链接文本
        this.setInnerText(elementA, ele.title);
        //将a标签元素添加到div标签元素中
        ele.appendChild(elementA);
        //新建一个文本覆盖层
        var newText = new Overlay({
            id:idText,
            //设置位置为当前鼠标点击的坐标
            position: coordinate,
            offset: offset,
            //覆盖层元素
            element: elementA
        });
        //将文本覆盖层添加到map中
        map.addOverlay(newText);
    },
    //添加覆盖标注
    addOverlayLabel(idOverLay,idText,ele,map,number,coordinate,offset) {
        //创建一个div元素
        // var elementDiv = document.createElement('div');
        // //设置div元素的样式类
        // elementDiv.className = 'marker';
        //设置div元素的title属性
        // elementDiv.title = number;
         ele.title = number;

        // //获取id为label的div标签
        // var overlay = document.getElementById('label');
        // //将新创建的div标签添加到overlay中
        // overlay.appendChild(ele);

        //创建一个a标签元素
        var elementA = document.createElement('a');
        //设置a标签的样式类
        elementA.className = 'addressOverlay';
        //设置a标签的链接地址
        // elementA.href = '#';
        //设置a标签的超链接文本
        this.setInnerText(elementA, ele.title);
        //将a标签元素添加到div标签元素中
        ele.appendChild(elementA);

        //新建一个覆盖层
        var newMarker = new Overlay({
            id:idOverLay,
            //设置位置为当前鼠标点击的坐标
            position: coordinate,
            //设置覆盖层与位置之间的匹配方式
            positioning: 'center-center',
            //覆盖层元素
            element: ele,
            //事件传播到地图视点的时候是否应该停止
            stopEvent: false
        });
        //将覆盖层添加到map中
        map.addOverlay(newMarker);
        //新建一个文本覆盖层
        var newText = new Overlay({
            id:idText,
            //设置位置为当前鼠标点击的坐标
            position: coordinate,
            offset: offset,
            //覆盖层元素
            element: elementA
        });
        //将文本覆盖层添加到map中
        map.addOverlay(newText);
    },
    // 判断经纬度代表的点是否在当前可视范围内---
    isInCurrentExtent (x, y) {
    },
    // 将像素点转化为经纬度
    toMap (x, y) {
      var pixel = [x, y]
      var coordinate = this.olmap.getCoordinateFromPixel(pixel)
      if (!coordinate) {
        return null
      }
      return {
        x: coordinate[0],
        y: coordinate[1]
      }
    },
       //创建标签的样式
    createLabelStyle(feature,imgSrc,scale,offset,fontStyle) {
      //返回一个样式
      return new Style({
          //把点的样式换成ICON图标
          image: new Icon({
              //控制标注图片和文字之间的距离
              anchor: [0.5, 40],
              //标注样式的起点位置
              anchorOrigin: 'top-right',
              //X方向单位：分数
              anchorXUnits: 'fraction',
              //Y方向单位：像素
              anchorYUnits: 'pixels',
              //偏移起点位置的方向
              offsetOrigin: 'top-right',
              //透明度
              scale: scale,
              // opacity: 0.65,
              //图片路径
              src: imgSrc
          }),
          //文本样式
          text: new Text({
              //对齐方式
              textAlign: 'center',
              //文本基线
              textBaseline: 'middle',
              //字体样式
              font:fontStyle,
              //文本内容
              text: feature.get('name'),//获取到前端传递的name属性值
              //填充样式
              fill: new Fill({
                  color: '#aa3300'
              }),
              offsetX:offset[0],
              offsetY:offset[1],
              //笔触
              stroke: new Stroke({
                  color: '#ffcc33',
                  width: 2
              })
          })
      });
    },
    //设置文本内容
    setInnerText(element, text) {
        if (typeof element.textContent == 'string') {
            element.textContent = text;
        } else {
            element.innerText = text;
        }
    },
    // 将经纬度点转化为像素点
    toScreen (x, y) {
      var coordinate = [x, y]
      var pixel = this.olmap.getPixelFromCoordinate(coordinate)
      if (!pixel) {
        return null
      }
      return {
        x: pixel[0],
        y: pixel[1]
      }
    },
    // 获取地图的视图对象
    getView () {
      return this.olmap.getView()
    },
    // 获取地图的所有图层对象--
    getAllLayers () {
      return this.olmap.getLayers().getArray()
    },
    // 获取添加到地图的所有图层的id-----
    getAllLayersID () {
      var layerIdArr = []
      var layers = this.getAllLayers()
      layers.forEach(function (_layer) {
        var id = _layer.get('id')
        layerIdArr.push(id)
      })
      return layerIdArr
    },
    // 根据图层id获取相应的图层对象----
    getLayer (layerId) {
      var layers = this.getAllLayers()
      var layer = null
      layers.forEach(function (_layer) {
        var id = _layer.get('id')
        if (id === layerId) {
          layer = _layer
        }
      })
      return layer
    },
    // 根据图层id判断相应图层是否已经添加地图中---
    isLayerExist (layerid) {
      return this.getLayer(layerid) == null
    },
    // 地图放大----
    zoomIn () {
      this.setLevel(this.getLevel() + 1)
    },
    // 地图缩小-----
    zoomOut () {
      this.setLevel(this.getLevel() - 1 >= 0 ? (this.getLevel() - 1) : 0)
    },
    // 根据配置文件添加图层
    addLayer (config) {
      var {
        id,
        name,
        isCluster = false,
        clusterDistance = 20,
        isAddToMap = true,
        z_index = 3
      } = config
      let layer = null
      if (this.getLayer(id)) {
        layer = this.getLayer(id)
      } else {
        var source = new VectorSource()
        if (isCluster) {
          source = new Cluster({
            source: new VectorSource(),
            distance: clusterDistance
          })
        }
        layer = new VectorLayer({
          source,
          id,
          name
        })
        if (isAddToMap) {
            this.olmap.addLayer(layer)
        }
      }
      layer.setZIndex(z_index)
      return layer
    },
    // 根据图层id删除地图-------
    removeLayer (id) {
      this.olmap.removeLayer(this.getLayer(id))
    },
    // 添加控件
    addControl (control) {
      this.olmap.addControl(control)
    },
    // 添加交互组件
    addInteraction (interaction, isActive = false) {
      this.olmap.addInteraction(interaction)
      interaction.setActive(isActive)
    },
    // 添加可视化组件------
    removeControl (control) {
      this.olmap.removeControl(control)
    },
    // 删除交互组件----
    removeInteraction (interaction) {
      this.olmap.removeInteraction(interaction)
    },
    getInteractions () {
      return this.olmap.getInteractions()
    },
    getControls () {
      return this.olmap.getControls()
    },
    // 获取所有的覆盖物----
    getOverlays () {
      return this.olmap.getOverlays()
    },
    // 添加覆盖物----
    addOverlay (overlay) {
      this.olmap.addOverlay(overlay)
    },
    // 删除覆盖物----
    removeOverlay (overlayer) {
      this.olmap.removeOverlay(overlayer)
    },
    // 根据id获取覆盖物-----
    getOverlayById (id) {
      return this.olmap.getOverlayById(id)
    },
    // 获取呢当前地图的视口----
    getViewport () {
      return this.olmap.getViewport()
    },
    // 根据像素点查询要素-----
    forEachFeatureAtPixel (pixel, callback) {
      this.olmap.forEachFeatureAtPixel(pixel, function (feature, layer) {
        callback(feature, layer)
      })
    },
    // 获取地图容器------
    getTargetElement () {
      return this.olmap.getTargetElement()
    },
    // 获取地图容器大小
    getSize () {
      return this.olmap.getSize()
    },
    // 判断该像素点是否能拾取要素对象----
    hasFeatureAtPixel (pix) {
      return this.olmap.hasFeatureAtPixel(pix)
    },
    // 清除id对应的图层的所有要素对象----
    clearLayerFeatures (id) {
      this.getLayer(id).getSource().clear()
    },
    // 重新渲染地图------
    render() {
      this.olmap.render()
    }
  },
  mounted () {
    this.initMap()
  }, 
  destroyed () {
    console.log("destroy map")
    this.olmap = null
  }
}
</script>
<style scoped>
.addressOverlay{
   font-size:14px;
	 font-family:"微软雅黑";
}
</style>