当前位置: 首页 > article >正文

天地图的使用

最近在写项目的时候,用户需求有一个需要引入这样的非常详细的地图,因为走过了很多坑所以来记录一下。

为什么引入天地图

    最开始的时候,以我贫瘠的学识,我以为直接使用那个echarts的3d地图就可以了,确实我也尝试了一下,我发现并没有我想象的这么简单,我引入了echarts,它只有一个地球在旋转,完全不可以放大。

    后面上网搜索了一下,发现可以引用天地图

天地图的使用

    首先你肯定要登录吧,这个就不多说了

    然后,如果你要引用天地图里面的api,你必须要经过以下的流程:

   这样你就会得到一个key,这个key是用api最重要的一环

代码详解

页面区域:

<template>
    <div id="xtMap" class="xt-map"></div>
</template>

样式区域:

.xt-map {
    width: 100%;
    height: 100vh;
}

script区域:


<script>
import axios from 'axios';
import XTSData from '@/util/XTS.json';
import XiangtanData from '@/util/湘潭市.json';
export default {
    name: 'XiangtanMap',
    data() {
        return {
            map: null,
            polygonCoordinates: [], // 湘潭区域的边界坐标点
        };
    },
    mounted() {
        this.loadTiandituScript();
    },
    methods: {
        async loadTiandituScript() {
            const script = document.createElement('script');
            script.src = "http://api.tianditu.gov.cn/api?v=4.0&tk=你的key";
            script.onload = () => {
                console.log('天地图 API 脚本加载成功');
                if (typeof T === 'undefined') {
                    console.error('天地图 API 未正确加载');
                    return;
                }
                this.init();
            };
            script.onerror = () => {
                console.error('天地图 API 脚本加载失败');
            };
            document.head.appendChild(script);
        },
        async init() {
            try {
                await this.initTiandituMap(); // 初始化地图
            } catch (error) {
                console.error('Error initializing map:', error);
            }
        },
        async initTiandituMap() {
            const mapContainer = document.getElementById('xtMap');
            if (!mapContainer) {
                console.error('Map container not found');
                return;
            }
    
            const imageURL = "http://t0.tianditu.gov.cn/img_w/wmts?" +
                "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
                "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=你的key";
    
            const imageURLT = "http://t0.tianditu.gov.cn/cia_w/wmts?" +
                "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
                "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}" +
                "&tk=你的key";
    
            const lay = new T.TileLayer(imageURL, { minZoom: 0, maxZoom: 18 });
            const lay2 = new T.TileLayer(imageURLT, { minZoom: 0, maxZoom: 18 });
            const config = { layers: [lay, lay2] };
    
            this.map = new T.Map("xtMap", config);
            this.map.centerAndZoom(new T.LngLat(112.584052, 27.72973), 9.6);
            this.map.enableInertia();
    
            try {
                // 引入 util 目录下的 JSON 文件
    
    
                const countries = XTSData.features;
                if (countries) {
                    this.processBoundaries(countries, this.map);
                } else {
                    console.error('Boundary data features in XTS.json is undefined');
                }
    
                const shiyanCountries = XiangtanData.features;
                if (shiyanCountries) {
                    this.processBoundaries(shiyanCountries, this.map);
                } else {
                    console.error('Boundary data features in 湘潭市.json is undefined');
                }
            } catch (error) {
                console.error('Error loading boundary data:', error);
            }
        },
        processBoundaries(countries, map) {
            countries.forEach(item => {
                var districtName = item.properties.name;
                var bounds = item.geometry.coordinates[0][0];
                console.log(`${districtName} Boundary coordinates:`, bounds); // 输出坐标点数组

                var style = {
                    color: 'rgb(127,181,255)',
                    weight: 2,
                    opacity: 1,
                    lineStyle: 'solid',
                    fillColor: 'rgb(127,181,255,0.5)',
                    fillOpacity: 0.3
                };

                var points = bounds.map(line => new T.LngLat(line[0], line[1]));
                console.log(`${districtName} Polygon points:`, points); // 输出多边形的坐标点数组

                var polygon = new T.Polygon(points, style);
                // 将多边形添加到地图上
                map.addOverLay(polygon);
            });
        }
    }
};
</script>

说明:

我主要引入的是湖南湘潭这部分。

import axios from 'axios';
import XTSData from '@/util/XTS.json';
import XiangtanData from '@/util/湘潭市.json';

因为我还没有连接后端,所以一些json文件我是存在本地的。

XTSData是从XTS.json文件导入的数据,包含某些区域的边界信息。

XiangtanData:从湘潭市.json文件导入的数据,包含湘潭市的边界信息。

export default {
    name: 'XiangtanMap',
    data() {
        return {
            map: null,
            polygonCoordinates: [], // 湘潭区域的边界坐标点
        };
    },
    mounted() {
        this.loadTiandituScript();
    },
    methods: {
        // ..._methods go here...
    }
};

vue组件的定义

  async loadTiandituScript() {
            const script = document.createElement('script');
            script.src = "http://api.tianditu.gov.cn/api?v=4.0&tk=你的key";
            script.onload = () => {
                console.log('天地图 API 脚本加载成功');
                if (typeof T === 'undefined') {
                    console.error('天地图 API 未正确加载');
                    return;
                }
                this.init();
            };
            script.onerror = () => {
                console.error('天地图 API 脚本加载失败');
            };
            document.head.appendChild(script);
        },

这个方法是进行通过动态创建和添加<script>元素来加载天地图API,并在加载成功后初始化地图。

    async init() {
            try {
                await this.initTiandituMap(); // 初始化地图
            } catch (error) {
                console.error('Error initializing map:', error);
            }
        },

初始化函数,调用初始化地图函数

 async initTiandituMap() {
            const mapContainer = document.getElementById('xtMap');//获取页面上的元素
            if (!mapContainer) {
                console.error('Map container not found');
                return;
            }
    
            const imageURL = "http://t0.tianditu.gov.cn/img_w/wmts?" +
                "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
                "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=你的key";
    
            const imageURLT = "http://t0.tianditu.gov.cn/cia_w/wmts?" +
                "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
                "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}" +
                "&tk=你的key";
    
            const lay = new T.TileLayer(imageURL, { minZoom: 0, maxZoom: 18 });
            const lay2 = new T.TileLayer(imageURLT, { minZoom: 0, maxZoom: 18 });
            const config = { layers: [lay, lay2] };
    
            this.map = new T.Map("xtMap", config);
            this.map.centerAndZoom(new T.LngLat(112.584052, 27.72973), 9.6);
            this.map.enableInertia();
    
            try {
                // 引入 util 目录下的 JSON 文件
    
    
                const countries = XTSData.features;
                if (countries) {
                    this.processBoundaries(countries, this.map);
                } else {
                    console.error('Boundary data features in XTS.json is undefined');
                }
    
                const shiyanCountries = XiangtanData.features;
                if (shiyanCountries) {
                    this.processBoundaries(shiyanCountries, this.map);
                } else {
                    console.error('Boundary data features in 湘潭市.json is undefined');
                }
            } catch (error) {
                console.error('Error loading boundary data:', error);
            }
        },

初始化地图函数,一些关键的步骤:

const imageURL = "http://t0.tianditu.gov.cn/img_w/wmts?...&tk=你的key";
const imageURLT = "http://t0.tianditu.gov.cn/cia_w/wmts?...&tk=你的key";

定义地图图层:

imageURL 是天地图影像图层的URL,包含服务地址、请求参数和您的天地图密钥(tk)。imageURLT 是天地图影像注记图层的URL,同样包含服务地址、请求参数和密钥。

会自动产生T,叫什么图层

const lay = new T.TileLayer(imageURL, { minZoom: 0, maxZoom: 18 });
const lay2 = new T.TileLayer(imageURLT, { minZoom: 0, maxZoom: 18 });
const config = { layers: [lay, lay2] };

创建地图图层:

lay 和 lay2 分别是影像图层和影像注记图层的实例。

config 对象配置了地图的图层,包括 lay 和 lay2

this.map = new T.Map("xtMap", config);
this.map.centerAndZoom(new T.LngLat(112.584052, 27.72973), 9.6);
this.map.enableInertia();

初始化地图:

new T.Map("xtMap", config) 创建一个新的天地图实例,并将其绑定到地图容器上。

centerAndZoom 方法设置地图的中心点和初始缩放级别,具体数据可以去网络上寻找

enableInertia 方法启用地图的惯性拖动效果。

try {
    // 引入 util 目录下的 JSON 文件
    const countries = XTSData.features;
    if (countries) {
        this.processBoundaries(countries, this.map);
    } else {
        console.error('Boundary data features in XTS.json is undefined');
    }

    const shiyanCountries = XiangtanData.features;
    if (shiyanCountries) {
        this.processBoundaries(shiyanCountries, this.map);
    } else {
        console.error('Boundary data features in 湘潭市.json is undefined');
    }
} catch (error) {
    console.error('Error loading boundary data:', error);
}

加载边界数据:

try 块尝试执行代码,捕获可能出现的错误。

XTSData.features 和 XiangtanData.features 分别是从JSON文件中获取的边界数据特征。

this.processBoundaries 方法用于在地图上处理和显示这些边界数据。

如果边界数据未定义或加载过程中出现错误,将输出相应的错误信息。

一些json文件和源码xixloveixixi/tianditu: 这里面是我在天地图中用到的json文件以及源码


http://www.kler.cn/a/582036.html

相关文章:

  • 【机械视觉】C#+VisionPro联合编程———【五、硬币检测小项目实现(C#+VisionPro联合编程和csv文件格式操作)】
  • Vue主流的状态保存框架对比
  • git无法提交解决方案--! [rejected] master -> master (non-fast-forward)
  • WLAN(无线局域网)安全
  • 《PyCharm 重命名项目文件时遇到 java.io.IOException 的终极解决方案》
  • [java]增强for循环
  • 误删/lib64/ld-linux-x86-64.so.2导致系统崩溃
  • php中JSON或数组到formData的键值对转换
  • Qt的Tcp通信
  • mysql的MGR
  • 基于生成式人工智能的网络安全主动防御技术(下)
  • C++ 编程基础:注释、字符串、输入输出、日期处理、修饰符
  • 2025最新软件测试面试八股文(含答案+文档)
  • CSS伸缩盒模型(弹性盒子)
  • 01 音视频知识学习(视频)
  • 写一个简单的SQL生成工具
  • 算法刷题--贪心算法
  • Sentinel-1 InSAR ISCE数据处理:stackSentinel.py 完全指南
  • python LLM工具包
  • API调试工具的无解困境:白名单、动态IP与平台设计问题