BaiduMap.vue 2.28 KB
Newer Older
hucy's avatar
hucy committed
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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
<template>
  <div
    id="allmap"
    :style="{ width: width + 'px', height: height + 'px' }"
  ></div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { isEmpty, cloneDeep } from 'src/common/utils';
interface Props {
  id: string;
  width: number;
  height: number;
  bMapPoint?: Array<number>; // 中心点坐标
  mapLevel?: number; // 地图级别
  navigationControl?: boolean; // 平移缩放控件
  overviewMapControl?: boolean; // 缩略地图控件
  scrollWheelZoom?: boolean; // 开启鼠标滚轮缩放
  scaleControl?: boolean; // 比例尺控件
}
const props = withDefaults(defineProps<Props>(), {
  id: 'map',
  width: 100,
  height: 100,
  bMapPoint: () => [],
  mapLevel: 12,
  navigationControl: false,
  overviewMapControl: false,
  scrollWheelZoom: false,
  scaleControl: false,
});

const bMapApi = ref(null);

const state = reactive({
  bMapPoint: cloneDeep(props.bMapPoint),
});

onMounted(async () => {
  let map = new (window as any).BMap.Map(props.id); // 创建Map实例
  bMapApi.value = map;

  let p = new Promise<void>(function (resolve) {
    if (isEmpty(props.bMapPoint)) {
      let myCity = new (window as any).BMap.LocalCity();
      myCity.get((res: any) => {
        state.bMapPoint.push(res.center.lng);
        state.bMapPoint.push(res.center.lat);
        resolve();
      });
    } else {
      resolve();
    }
  });
  p.then(() => {
    map.centerAndZoom(
      new (window as any).BMap.Point(state.bMapPoint[0], state.bMapPoint[1]),
      props.mapLevel
    );
  });
  if (props.navigationControl) {
    map.addControl(new (window as any).BMap.NavigationControl());
  }
  if (props.overviewMapControl) {
    map.addControl(new (window as any).BMap.OverviewMapControl());
  }
  if (props.scaleControl) {
    map.addControl(new (window as any).BMap.ScaleControl());
  }
  if (props.scrollWheelZoom) {
    map.enableScrollWheelZoom(true);
  }
  // 添加地图类型控件
  //   map.addControl(
  //     new window.BMap.MapTypeControl({
  //       mapTypes: [window.BMAP_NORMAL_MAP, window.BMAP_HYBRID_MAP],
  //     })
  //   );
  // map.setCurrentCity('成都'); // 设置地图显示的城市 仅当设置城市信息时,MapTypeControl的切换功能才能可用
});
defineExpose({
  bMapApi,
});
</script>

<style lang="scss" scoped></style>