<template>
<div>
  <div v-if="!hasBmView" ref="view" style="width: 100%; height: 100%">
  </div>
  <slot></slot><!--此处的插槽放置地下的功能控件按钮-->
</div>
</template>
<script>
import { createApp } from 'vue'
import { mapStore } from '../stores/mapStore'
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 { transform,transformExtent } from 'ol/proj'
import qs from 'qs'
import Overlay from 'ol/Overlay'
import {clearSpatial,addVector} from '../base/poiQuery'
import  Overview  from '../controls/Overview'
import  Compass  from '../controls/Compass'
import  CanvasScaleLine  from '../controls/CanvasScaleLine'
import  ZoomSlider  from '../controls/ZoomSlider'
// import {PanZoomBar} from 'ol/control'
// import {ol} from 'ol';
import { wgs84Toweb3857, web3857ToWgs84 } from '../base/factory.js'
import eventBus from '../eventBus/eventBus.js'
const _panFactor = 0.0005
let 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) {
      let 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))
      }  
   },
   // 监听地图中心点---
   center (val) {
      const { olmap, center, projection } = this
      olmap.getView().setCenter(transform(center, 'EPSG:4326', projection))
    },
    // 监听地图缩放级别----
    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) {
      const { projection } = this
      this.olmap.getView().fit(transformExtent(mapExtent, 'EPSG:4326', projection))
    }
  },
  methods: {
    initMap() {
      let $el = this.$refs.view // 地图布局，地图是用容器渲染-------
      for (let $node of ((this.$slots.default && 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
      let { extent} = this
      if (extent && extent.length === 0) {
        extent = [-180,-85,180,85]
      }
      
      // let centerEPSG3857 = fromLonLat(center);
      let view = new View({//初始化时候的视角范围
        projection,//EPSG:3857
        center:transform(center, 'EPSG:4326', projection),//center也是EPSG3857
        zoom,
        minZoom,
        maxZoom,
        extent:transformExtent(extent, 'EPSG:4326', projection) // 可视范围限制
        // extent:transformExtent([-180,-90,180,90],'EPSG:4326','EPSG:3857'),
      })
      const map = new Map({
        target: $el,
        keyboardEventTarget:document,
        view,
        controls: defaultControls({attribution:false, zoom: false}),
        interactions: defaultInteractions().extend([
          new DragRotateAndZoom()
        ])
      })
      // 传递 范围后，中心点，级别定位地图失效，根据范围来缩放地图----
      // if (extent) {
      //   map.getView().fit(extent, map.getSize())
      // }
      let layer = null
      if(config.layers(mapType)){
         layer = config.layers(mapType)
      }
      if (layer) {
        map.addLayer(layer)
       // 添加鹰眼缩略图控件----
        // let ov = new Overview(
        //   {	layers: [layer],
        //     minZoom,
        //     maxZoom,
        //     zoom,
        //     center,
        //     projection
        //   })
        //   map.addControl(ov)
        // this.isOpenOverview?map.addControl(ov):map.removeControl(ov)
      }
      // 添加比例尺控件
      let 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())
      //添加罗盘控件
      // map.addControl(new Compass())
      this.olmap = map
      // const app = createApp({})
      // app.config.globalProperties.$map = map
      // app.config.globalProperties.$projection = projection
      mapStore.initMap(map)
      this.$emit('ready', {
        map
      })
      eventBus.emit('ready')
      // 地图移动结束事件--根据屏幕范围进行查询
      this.olmap.on('moveend', ev => {
        if(!this.olmap){
          return
        }
        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==',
        //     }
        //     let 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(let i = 0;i<domArr.length;i++){
        //               if(domArr[i].innerHTML.indexOf("地址")>-1){
        //                   domArr[i].style.display="none"
        //               }
        //           }
        //       }
        //   }
        let obj = []
        let center = this.olmap.getView().getCenter()
        let extent = this.olmap.getView().calculateExtent(this.olmap.getSize())
        let jingweidu = new transform([center[0],center[1]], projection, "EPSG:4326")
        obj[0] = jingweidu[0]
        obj[1] = jingweidu[1]
        this.$emit('zoomMoveEnd', { zoom, obj, extent })
      })
      // 地图开始移动事件
      this.olmap.on('movestart', ev => {
      })
      // 鼠标拖拽事件
      this.olmap.on('pointerdrag', ev => {
        let contextDom =document.getElementById("contextMenu");
        if(contextDom!=null||contextDom!=undefined){
          contextDom.remove();
        }
          let loc = ev.coordinate
          this.$emit('mousedrag', { lon: loc[0], lat: loc[1] });
          
          // this.olmap.handleResize_();//重新渲染地图
          // this.olmap.handleViewChanged_();
          // this.olmap.handleViewPropertyChanged_();
          // this.olmap.updateSize();
          // 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) { // 表示该要素是聚合要素-------
               // 获取该聚合要素类含有的要素的个数----
              let 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
        let jingweidu = new transform([obj.lon,obj.lat], projection, "EPSG:4326")
        obj.lon = jingweidu[0]
        obj.lat = jingweidu[1]
        this.$emit('mousemove', obj)
      })
      // 鼠标单击事件
      this.olmap.on('click', ev => {
        let contextDom =document.getElementById("contextMenu");
        if(contextDom!=null||contextDom!=undefined){
          // contextDom.remove();
          contextDom.style.visibility="hidden"
        }
        let loc = ev.coordinate
         //获取单选按钮的选项
        let type = $('input[name="label"]:checked').val();
        //获取位置坐标
        // let 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) { // 表示该要素是聚合要素-------
               // 获取该聚合要素类含有的要素的个数----
              let 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
          }
        }
        let jingweidu = new transform([obj.lon,obj.lat], projection, "EPSG:4326")
        obj.lon = jingweidu[0]
        obj.lat = jingweidu[1]
        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(transform([x, y], 'EPSG:4326', this.projection))
    },
    // 根据偏差定位地图-----
    centerAtWithOffset (x, y, offX, offY) {
      let _screenP = this.toScreen(x, y)
      _screenP.x = _screenP.x + offX
      _screenP.y = _screenP.y + offY
      let _mapP = this.toMap(_screenP.x, _screenP.y)
      this.centerAt(_mapP.x, _mapP.y)
    },
    // 设置地图缩放级别---
    setLevel (level) {
      this.olmap.getView().setZoom(level)
    },
    // 向左移动地图-----
    moveToLeft () {
      let view = this.olmap.getView()
      let mapCenter = view.getCenter()
      // 让地图中心的x值增加，即可使得地图向左移动，增加的值根据效果可自由设定
      mapCenter[0] += _panFactor
      view.setCenter(mapCenter)
      this.olmap.render()
    },
    // 向右移动地图-----
    moveToRight () {
      let view = this.olmap.getView()
      let mapCenter = view.getCenter()
      // 让地图中心的x值减少，即可使得地图向右移动，减少的值根据效果可自由设定
      mapCenter[0] -= _panFactor
      view.setCenter(mapCenter)
      this.olmap.render()
    },
    // 向上移动地图
    moveToUp () {
      let view = this.olmap.getView()
      let mapCenter = view.getCenter()
      // 让地图中心的y值减少，即可使得地图向上移动，减少的值根据效果可自由设定
      mapCenter[1] -= _panFactor
      view.setCenter(mapCenter)
      this.olmap.render()
    },
    // 向下移动地图
    moveToDown () {
      let view = this.olmap.getView()
      let 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 () {
      let 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并可移动
        //新建一个覆盖层
        let newMarker = new Overlay({
            id:id,
            //设置位置为当前鼠标点击的坐标
            position: transform(coordinate, 'EPSG:4326', this.projection),
            //设置覆盖层与位置之间的匹配方式
            positioning: 'center-center',//如果包含center这块可能是openlayers的一个bug数据量大了就卡
            // positioning:'top-left',
            //覆盖层元素
            element: element,
            //事件传播到地图视点的时候是否应该停止
            // stopEvent: false
        });
        //将覆盖层添加到map中
        this.olmap.addOverlay(newMarker);
        let _this = this;
        // display popup on click
          let 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====",transform(newMarker.values_.position, _this.projection, 'EPSG:4326'))
                _this.$emit('contextmenuPos',transform(newMarker.values_.position, _this.projection, 'EPSG:4326'))
              }
          });
          map.on('pointermove', function(evt) {//鼠标移动事件
            // let startPoint=iconFeature.getGeometry().getCoordinates();
              if (newMarker.get('dragging')) {
                let dd2=map.getPixelFromCoordinate(evt.coordinate);
                // let newX=dd2[0]-0;//减去偏移量
                // let newY=dd2[1]-(-50);
                let newX=dd2[0]-0;//减去偏移量
                let newY=dd2[1]-(0);
                let 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);
          //       let dd2=map.getPixelFromCoordinate(evt.coordinate);
          //       let newX=dd2[0]-0;//减去偏移量
          //       let newY=dd2[1]-(0);
          //       let newPoint=map.getCoordinateFromPixel([newX,newY]);
          //       console.log("endPos====",newPoint)
          //       _this.$emit('contextmenuPos', newPoint)
          //     }
          // });
    },
    /*添加Feature矢量标签并且可以以select的方式移动——罗旭*/
    addVectorLabelJG(map,markerObj,offset) {//添加矢量标签
          //初始化一个新的点要素
          let newFeature = new Feature({//features中可以放attributes
              geometry: new Point(transform([markerObj.lon,markerObj.lat], 'EPSG:4326', this.projection)),
              name: markerObj.name,
              attributes:markerObj
          });
          //设置点的样式
          newFeature.setStyle(this.createLabelStyle(newFeature,markerObj.imgSrc,markerObj.scale,offset,markerObj.fontStyle));//这块添加图片
          //初始化矢量数据源
          let vectorSource = new VectorSource({
              //指定要素
              features: [newFeature]
          });
          //初始化矢量图层
          let 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)
          let select = new Select({
             id:"slectMarker",
             layers:[vectorLayer],
          });//选择图形interaction
          this.olmap.addInteraction(select);//不可能每次进来一次添加一次
          let translate = new Translate({//拖拽移动interaction
              id:"translateMarker",
              features: select.getFeatures(),//拖拽的为选择的要素
              hitTolerance:0,
          });
          this.olmap.addInteraction(translate);//不可能每次进来一次添加一次
          let _this = this;
          translate.on('translateend',function(f){
              //  _this.$emit('endPos', carType + "_" + _this.countTwo)
              _this.$emit('moveEndPos', f.coordinate)
              console.log("ooooooooooooooooo");//拖拽完成事件，可以获取拖拽后的要素
          });
          // let 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"
          }
          //初始化一个新的点要素
          let newFeature = new Feature({//features中可以放attributes
              geometry: new Point(coordinate),
              name: '标注点',
              attributes:markerObj
          });
          //设置点的样式
          newFeature.setStyle(this.createLabelStyle(newFeature));//这块添加图片
          //初始化矢量数据源
          let vectorSource = new VectorSource({
              //指定要素
              features: [newFeature]
          });
          //初始化矢量图层
          let 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)
          let select = new Select({
             id:"slectMarker",
             layers:[vectorLayer],
          });//选择图形interaction
          this.olmap.addInteraction(select);//不可能每次进来一次添加一次
          let translate = new Translate({//拖拽移动interaction
              id:"translateMarker",
              features: select.getFeatures(),//拖拽的为选择的要素
              hitTolerance:0,
          });
          this.olmap.addInteraction(translate);//不可能每次进来一次添加一次
          let _this = this;
          translate.on('translateend',function(f){
              _this.$emit('moveEndPos', f.coordinate)
              console.log("ooooooooooooooooo");//拖拽完成事件，可以获取拖拽后的要素
          });
          //将矢量图标添加到地图之后提交到后端nodejs
          //this.$emit('returnMarkerFlag', markerObj)//这块用不用给前端返回暂时先待定
          // let attr = obj.feature.values_.attributes
          //获取到地图标记图标后的点击图标属性信息
          let 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元素
        // let elementDiv = document.createElement('div');
        // //设置div元素的样式类
        // elementDiv.className = 'marker';
        //设置div元素的title属性
        // elementDiv.title = number;
         ele.title = number;
        // //获取id为label的div标签
        // let overlay = document.getElementById('label');
        // //将新创建的div标签添加到overlay中
        // overlay.appendChild(ele);
        //创建一个a标签元素
        let elementA = document.createElement('a');
        //设置a标签的样式类
        elementA.className = 'addressOverlay';
        //设置a标签的链接地址
        // elementA.href = '#';
        //设置a标签的超链接文本
        this.setInnerText(elementA, ele.title);
        //将a标签元素添加到div标签元素中
        ele.appendChild(elementA);
        //新建一个文本覆盖层
        let newText = new Overlay({
            id:idText,
            //设置位置为当前鼠标点击的坐标
            position: transform(coordinate, 'EPSG:4326', this.projection),
            offset: offset,
            //覆盖层元素
            element: elementA
        });
        //将文本覆盖层添加到map中
        map.addOverlay(newText);
    },
    //添加覆盖标注
    addOverlayLabel(idOverLay,idText,ele,map,number,coordinate,offset) {
        //创建一个div元素
        // let elementDiv = document.createElement('div');
        // //设置div元素的样式类
        // elementDiv.className = 'marker';
        //设置div元素的title属性
        // elementDiv.title = number;
         ele.title = number;

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

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

        //新建一个覆盖层
        let newMarker = new Overlay({
            id:idOverLay,
            //设置位置为当前鼠标点击的坐标
            position: transform(coordinate, 'EPSG:4326', this.projection),
            //设置覆盖层与位置之间的匹配方式
            positioning: 'center-center',
            //覆盖层元素
            element: ele,
            //事件传播到地图视点的时候是否应该停止
            stopEvent: false
        });
        //将覆盖层添加到map中
        map.addOverlay(newMarker);
        //新建一个文本覆盖层
        let newText = new Overlay({
            id:idText,
            //设置位置为当前鼠标点击的坐标
            position: transform(coordinate, 'EPSG:4326', this.projection),
            offset: offset,
            //覆盖层元素
            element: elementA
        });
        //将文本覆盖层添加到map中
        map.addOverlay(newText);
    },
    // 判断经纬度代表的点是否在当前可视范围内---
    isInCurrentExtent (x, y) {
    },
    // 将像素点转化为经纬度
    toMap (x, y) {
      let pixel = [x, y]
      let 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) {
      let coordinate = [x, y]
      let 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 () {
      let layerIdArr = []
      let layers = this.getAllLayers()
      layers.forEach(function (_layer) {
        let id = _layer.get('id')
        layerIdArr.push(id)
      })
      return layerIdArr
    },
    // 根据图层id获取相应的图层对象----
    getLayer (layerId) {
      let layers = this.getAllLayers()
      let layer = null
      layers.forEach(function (_layer) {
        let 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) {
      let {
        id,
        name,
        isCluster = false,
        clusterDistance = 20,
        isAddToMap = true,
        z_index = 3
      } = config
      let layer = null
      if (this.getLayer(id)) {
        layer = this.getLayer(id)
      } else {
        let 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()
  }, 
  unmounted () {
    console.log("destroy map")
    this.olmap = null
  }
}
</script>
<style scoped>
.addressOverlay{
   font-size:14px;
	 font-family:"思源黑体";
}
</style>