欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 维修 > 关于天地图新手使用

关于天地图新手使用

2024/10/25 2:26:55 来源:https://blog.csdn.net/m1011815213/article/details/141167724  浏览:    关键词:关于天地图新手使用

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.longitudelatitude.value = props.data.latitudeif (!map.value) {const T = window.Tmap.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); // 使用 addOverLaymarker.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); // 使用 addOverLaythis.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差别不大

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com