openlayers加载图片图层(base64图片或geojson)

背景:后台返回base64加密图片

      this.dzmData = 'data:image/jpeg;base64,' + data  //data :后台返回值
      this.drawRaindata('data:image/jpeg;base64,' + data)
    drawRaindata(data) {
      // 图片的位置
      var extent = [78.3937045720084882, 26.6196231671198298, 99.1151731627114430, 36.2507410702885622]
      var name = 'rain'
      var imageLayer = new Image({
        layerName: name,
        visible: false,
        source: new ImageStatic({
          url: data,
          imageExtent: extent
        })
      })
      this.addLayer(name, imageLayer)
    }

geojson数据加载时

    drawRaindata(data) {
      var name = 'rain'
      const features = new GeoJSON().readFeatures(data)
      console.log(typeof features)
      features.forEach(feature => {
        this.dzmStyle(feature)
      })
      //与图片加载source的不同
      const vectorSource = new VectorSource({
        features: features
      })
      var layer = new VectorLayer({
        layerName: name,
        source: vectorSource,
        visible: false // setVisible(true/false)控制显示隐藏
        // style: this.dzmStyle()
      })
      this.addLayer(name, layer)
      this.getLayerByLayerName(name)
    },
    dzmStyle(feature) {
      const max = feature.get('highValue')
      const min = feature.get('lowValue')
      const avg = (max + min) / 2
      // console.log(avg)
      let cr = 'rgba(255, 255, 255, 0)' //默认透明
      cr = this.getFeaturesColor(avg)
      feature.setStyle(new Style({
        fill: new Fill({
          color: cr
        })
      }))
    },

封装简易方法

    // 降雨等值面(更具雨量值设置颜色)
    getFeaturesColor(avg) {
      if (avg <= 1) {
        return 'rgba(255, 255, 255, 0)'
      } else if (avg > 1 && avg < 5) {
        return '#A6F28E'
      } else if (avg >= 5 && avg < 10) {
        return '#258C30'
      } else if (avg >= 10 && avg < 15) {
        return '#61B8FF'
      } else if (avg >= 15 && avg < 30) {
        return '#0000E1'
      } else if (avg >= 30 && avg < 50) {
        return '#FA00FA'
      } else if (avg >= 50) {
        return '#880015'
      } else {
        return 'rgba(255, 255, 255, 0)'
      }
    },

    //添加图层
    addLayer(layerName, layer) {
      this.layers[layerName] = layer
      this.map.addLayer(layer)
    },
    //移除图层
    removeLayer(layerName) {
      const layer = this.layers[layerName]
      if (layer) {
        this.map.removeLayer(layer)
      }
    },
    //获取指定图层
    getLayerByLayerName(layerName) {
      let targetLayer = null
      const me = this
      if (Vue.prototype.map) {
        const layers = Vue.prototype.map.getLayers().getArray()
        layers.forEach((layer, index) => {
          const _layerName = layers[index].values_.layerName
          if (_layerName === layerName) {
            me.idx = index
            targetLayer = layers[index]
          }
        })
      }
      return targetLayer
    }