<script>
import Group from 'ol/layer/Group'
import TileImage from 'ol/source/TileImage'
import Tile from 'ol/source/Tile'
import TileGrid from 'ol/tilegrid/TileGrid'
import { getWidth, getTopLeft} from 'ol/extent'
export default {
  name: 'sl-tdt-layer',
  render (h) { },
  props: {
  },
  watch: {
  },
  methods: {
    load () {
      const { map } = this
      var layer = new Group({layers: [this.getTdtLayer('img_c'), this.getTdtLayer('cia_c')]})
      this.originInstance = layer
      map.addLayer(layer)
    },
    getTdtLayer(lyr) {
      const { map } = this
      var url = 'http://t4.tianditu.com/DataServer?T=' + lyr + '&x={x}&Y={y}&L={z}'
      var projectionExtent = [ -180, -90, 180, 90 ]
      var maxResolution = (getWidth(projectionExtent) / (256 * 2))
      var resolutions = new Array(19)
      for (var z = 0; z < 19; ++z) {
        resolutions[z] = maxResolution / Math.pow(2, z)
      }
      var tileOrigin = getTopLeft(projectionExtent)
      var layer = new Tile({
        extent: projectionExtent,
        source: new TileImage({
          crossOrigin: 'anonymous',
          tileUrlFunction: function(tileCoord) {
            var z = tileCoord[0] + 1
            var x = tileCoord[1]
            var y = -tileCoord[2] - 1
            var n = Math.pow(2, z + 1)
            x = x % n
            if (x * n < 0) {
              x = x + n
            }
            return url.replace('{z}', z.toString())
                                .replace('{y}', y.toString())
                                .replace('{x}', x.toString())
          },
          projection: map.projection,
          tileGrid: new TileGrid({
            origin: tileOrigin,
            resolutions: resolutions,
            tileSize: 256
          })
        })
      })
      layer.set('title', 'tdtMap')
      return layer
    }
  }
}
</script>
