vue3 高德安徽省边界 密钥必须添加否则会出现无法使用DistrictSearch的方法也不报错

<template>
  <div class="centermap" ref="mapContainer"></div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';

const props = defineProps<{
  title: number | string;
  mapContainer: HTMLElement | null;
}>();

const mapContainer = ref<HTMLElement | null>(null);
const map = ref<any>(null);
const AMap_P = ref<any>(null);


function initMap() {
  if (!mapContainer.value) {
    console.log("Map container is not defined");
    return;
  }
  window._AMapSecurityConfig = {
    securityJsCode: "申请的密钥",
  };
  AMapLoader.load({
    key: '申请的key值',
    version: '2.0',
    plugins: ['AMap.DistrictSearch'],
  })
    .then((AMap) => {
      console.log("AMap loaded");
      AMap_P.value = AMap;
      map.value = new AMap.Map(mapContainer.value, {
        viewMode: '2D',
        zoom: 7.8,
        center: [118.92582075393364, 30.540301602456402],
        mapStyle: "amap://styles/darkblue",
      });

      const districtSearch = new AMap.DistrictSearch({
        subdistrict: 0,   //获取边界不需要返回下级行政区
        extensions: 'all',  //返回行政区边界坐标组等具体信息
        level: 'province'  //查询行政级别为 省
      });

      console.log("districtSearch instance created:", districtSearch);

      // 调用 search 方法前的调试信息
      console.log("Before search method");

      // 调用 search 方法
      districtSearch.search("安徽省", function (status: string, result: any) {
        // 回调函数的调试信息
        console.log("Search callback entered with status:", status);

        if (status === 'complete' && result.districtList.length) {
          const bounds = result.districtList[0].boundaries;
          console.log("bounds:", bounds);

          if (bounds) {
            const polygons = bounds.map((boundary: any) => new AMap.Polygon({
              strokeWeight: 2,
              path: boundary,
              fillOpacity: 0.4,
              fillColor: '#80d8ff',
              strokeColor: '#fffff'
            }));

            map.value.add(polygons);
            map.value.setFitView(polygons); // 视口自适应
          } else {
            console.error('No boundaries found for 安徽省');
          }
        } else {
          console.error('Failed to get district boundaries:', result);
        }
      });

      // 调用 search 方法后的调试信息
      console.log("After search method");
    })
    .catch((error) => {
      console.error('Failed to load AMap:', error);
    });
}

onMounted(() => {
  mapContainer.value = document.querySelector('.centermap');
  initMap();
});
</script>

<style scoped lang="scss">
.centermap {
  width: 100%;
  height: 100%;
  position: absolute;
}
</style>
posted @ 2024-06-11 14:26  张甜瓜  阅读(3)  评论(0编辑  收藏  举报