关于天地图新手使用

1分钟带你了解学习天地图 适用新手 

天地图API (tianditu.gov.cn) 文档api  先去注册key

把脚本放到index.html文件里面

<!-- 天地图的官网申请的tk -->
<script src="http://api.tianditu.gov.cn/api?v=4.0&tk=申请的key" type="text/javascript"></script>

废话不多说 直接来代码

vue3写法

<template>
  <div id="mapDiv" class="map"></div>
</template>

<script setup>
import { ref, watch, onMounted, nextTick } from "vue"
import axios from 'axios';
const props = defineProps({
  data: {
    type: Object,
    default: () => {
      return {
        longitude: "113.762375",
        latitude: "39.761003"
      }
    }
  },
  title: {
    type: String,
    default: "北京天安门"
  }
})

const map = ref(null)
const zoom = ref(16)
let longitude = ref("")
let latitude = ref("")

const marker = ref(null);
const label = ref(null);

watch(
  () => props.data,
  (newValue, oldValue) => {
    initLoad()
  }
)
const initLoad = () => {
  // 获取经纬度及名称
  longitude.value = props.data.longitude
  latitude.value = props.data.latitude

  if (!map.value) {
    const T = window.T
    map.value = new T.Map("mapDiv", {
      // projection: "EPSG:4326",
      zoom: zoom.value, //设置默认放大缩小
      center: new T.LngLat(longitude.value, latitude.value) //设置当前地图中心点
    })

    // 添加点击事件监听器 点击跳转过去
    map.value.on('click', (e) => {
      // 更新地图中心
      longitude.value = e.lnglat.lng;
      latitude.value = e.lnglat.lat;
      map.value.panTo(e.lnglat);

      // 清除所有覆盖物
      let newMarker = map.value.getOverlays(); 
      newMarker.forEach((i)=>{
        console.log('i',i);
        if (i.id == 'oneId') {
          map.value.removeOverLay(i)
        } else{
          console.log('谁也不删');
        }
      })
      console.log('newMarker--地图上的所有点',newMarker);

      // 重新添加新的标记点
      addMarkers();
    });
    addMarkers();
  } else {
    map.value.panTo(new T.LngLat(longitude.value, latitude.value))
  }

  addMarkers()
}


// 添加标记点
const addMarkers = () => {
  // 更新图标实例
  const icon = new T.Icon({
    iconUrl: "src/assets/images/projectKanban/btn-bg-border.svg",
    iconSize: new T.Point(27, 27),
    iconAnchor: new T.Point(10, 25)
  });

  const point = new T.LngLat(longitude.value, latitude.value);
  marker.value = new T.Marker(point, icon); // 创建标注

  map.value.addOverLay(marker.value); // 使用 addOverLay
  marker.value.id = 'oneId'//添加id 确定要删除那个标点 用来区分

  handleSearch()//地址解析当前位置名称

  // 添加文字标签
  // label.value = new T.Label({
  //   text: props.title,
  //   position: new T.LngLat(longitude.value, latitude.value),
  //   offset: new T.Point(-60, 20)
  // });
  // map.value.addOverLay(label.value);
}

const handleSearch = async () => {
  try {
    const apiKey = '123456'; // 天地图 API 密钥
    let params = {
      lon: longitude.value,
      lat: latitude.value,
      ver: 1
    }
    const postStr = JSON.stringify(params);
    const url = `http://api.tianditu.gov.cn/geocoder?postStr=${encodeURIComponent(postStr)}&type=geocode&tk=${apiKey}`;

    const response = await axios.get(url);

    if (response.status === 200) {
      console.log('Geocoding result:', response.data.result);
      let res = response.data.result

      // 添加文字标签
      label.value = new T.Label({
        text: res.addressComponent.poi,
        position: new T.LngLat(longitude.value, latitude.value),
        offset:new T.Point(0, -20) // 居中于标记点上方
      });
      map.value.addOverLay(label.value);
      label.value.id = 'oneId'//添加id 确定要删除那个标点 用来区分


      // 处理响应数据
    } else {
      console.error('Request failed with status:', response.status);
    }
  } catch (error) {
    console.error('Error fetching geocoding data:', error.message);
  }
};

onMounted(async () => {
  await nextTick()
  initLoad()
})
</script>

<style>
.map {
  width: 100%;
  height: 380px;
}    
</style>

vue2写法

<template>
  <div id='mapDiv' class="map"></div>
</template>
  
<script>
export default {
  name: "AmendProject",
  data() {
    return {
        tdtMap:{},//创建的地图map
      
    }
  },
  created(){
      this.getAddress()//获取当前位置 设置地图中心店
  },
  mounted(){
    //这里的initMap可以在拿到经纬度之后调用  也可以过去当前用户位置信息去调用
    // setTimeout(() => {
    //     this.initMap();
    // }, 500); // 延迟 0.5 秒以确保 API 加载完成
  },
  methods: {
    getAddress(){
      //利用浏览器Api进行获取位置信息
       navigator.geolocation.getCurrentPosition(
        position => {
          if (position.coords) {
            this.centerMap = {
              lng: position.coords.longitude,
              lat: position.coords.latitude,
            };
            //延时不要删除
            setTimeout(()=>{
              this.initMap()
            },500)
          }
        },
        error => {
          this.centerMap = {
            lng: 116.39128, // 默认经度
            lat: 39.90675   // 默认纬度
          };
          //延时不要删除
          setTimeout(()=>{
            this.initMap()
          },500)
          console.error('获取位置失败:', error);
        },
        { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 }
      );
    },
     // 创建天地图
    initMap() {
      try {
        let T = window.T;

        // 检查 T 对象是否存在
        if (typeof T === 'undefined' || !T.Map) {
          console.error('T object is not defined.');
          return;
        }

        // 确保 T 对象存在
        this.tdtMap = new T.Map("tdtMapDivID") // 使用正确的 ID
        // 设置显示地图的中心点和级别
        this.tdtMap.centerAndZoom(new T.LngLat(this.centerMap.lng, this.centerMap.lat), 15)

        //创建对象  逆地址解析用到 如果不需要可以不用
		    this.geocoder = new T.Geocoder();

        // 添加点击事件监听器
        this.tdtMap.on('click', (e) => {
          // 更新地图中心
          this.centerMap = e.lnglat;//修改经纬度

          this.tdtMap.panTo(e.lnglat);//设置中心点
          // 清除所有覆盖物
          let newMarker = this.tdtMap.getOverlays(); //获取当前地图的所有点
          newMarker.forEach((i)=>{
            // 这里通过id进行删除 这个id是根据你创建marker的时候设置的唯一标识
            if (i.id == 'oneId') {
              this.tdtMap.removeOverLay(i)
            } else{
              console.log('谁也不删');
            }
          })

          // 删除完成后  再次重新添加新的标记点
          this.addMarkers();
        })
        this.addMarkers()
      } catch (error) {
        console.log('error',error); 
      }
    },
    // 设置标点
    addMarkers(){
      this.tdtMap.panTo(this.centerMap);//设置中心点
      //设置图标
      const icon = new T.Icon({
        iconUrl: "src/assets/images/projectKanban/btn-bg-border.svg",
        iconSize: new T.Point(27, 27),
        iconAnchor: new T.Point(10, 25)
      });
      const point = new T.LngLat(this.centerMap.lng, this.centerMap.lat);
      this.marker = new T.Marker(point, icon); // 创建标注

      this.tdtMap.addOverLay(this.marker); // 使用 addOverLay
      this.marker.id = 'oneId'//添加id 确定要删除那个标点 用来区分
      // this.marker.enableDragging()//可拖拽点
    },

    //城市下拉选变化
    cascaderElChange(e){
       this.mapCenterText = '河南省郑州市金水区星星充电站'
       this.searchAddress()
    },
    searchAddress(){
      this.tdtMap.clearOverLays();//清除所有标记
		  this.geocoder.getPoint(this.mapCenterText, this.searchResult);//逆地址
    },
    searchResult(result){
      if(result.getStatus() == 0){
        this.tdtMap.panTo(result.getLocationPoint(), 16);
        //创建标注对象
        let marker = new T.Marker(result.getLocationPoint());
        marker.id = 'oneId'//添加id 方便删除区分
        //向地图上添加标注
        this.tdtMap.addOverLay(marker);
      }else{
        alert(result.getMsg());
      }
    },
  }
</script>
    
<style>
.map {
  width: 100%;
  height: 380px;
}    
</style>

方法都可以结合使用    vue3和vue2差别不大

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值