All files / tile-layer/src useTileLayer.ts

35% Statements 7/20
5.55% Branches 1/18
25% Functions 1/4
35% Lines 7/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54                  1x 1x 1x   1x                                                 1x 1x             1x              
import { useEffect, useState } from 'react';
import { useMapContext } from '@uiw/react-baidu-map-map';
import { TileLayerProps } from './';
 
export interface UseTileLayer extends TileLayerProps {}
/**
 * https://lbsyun.baidu.com/jsdemo.htm#g0_2
 */
export function useTileLayer(props = {} as UseTileLayer) {
  const [tileLayer, setTileLayer] = useState<BMap.TileLayer>();
  const { transparentPng = true, tileUrlTemplate, copyright, zIndex } = props;
  const { map } = useMapContext();
 
  useEffect(() => {
    if (map && !tileLayer) {
      const instance = new BMap.TileLayer({
        transparentPng,
        tileUrlTemplate,
        copyright,
        zIndex,
      });
      if (!!props.getTilesUrl) {
        instance.getTilesUrl = props.getTilesUrl;
      }
      if (!!props.getCopyright) {
        instance.getCopyright = props.getCopyright;
      }
      map.addTileLayer(instance);
      setTileLayer(instance);
      return () => {
        if (instance) {
          map.removeTileLayer(instance);
        }
      };
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [map]);
 
  const [visiable, setVisiable] = useState(props.visiable);
  useEffect(() => {
    if (map && tileLayer) {
      visiable ? map.addTileLayer(tileLayer) : map.removeTileLayer(tileLayer);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visiable, map]);
 
  return {
    tileLayer,
    setTileLayer,
    visiable,
    setVisiable,
  };
}