uniapp 使用天地图api
时间: 2025-01-08 09:00:55 浏览: 81
### 如何在 UniApp 中使用天地图 API
#### 创建项目结构并配置环境变量
为了确保安全性和灵活性,在 `manifest.json` 文件中的 environment 配置项里设置 TDT_KEY 环境变量来保存申请到的地图 Key。
```json
{
"environment": {
"TDT_KEY": "your_tdt_key"
}
}
```
#### 引入必要的资源文件
通过 npm 或者 CDN 的方式引入天地图所需的 JavaScript 库。推荐采用官方提供的最新版本以获得更好的兼容性和支持[^3]。
#### 编写 HTML 结构
定义一个容器用于承载地图展示区域,并赋予其特定 ID 方便后续操作:
```html
<template>
<view class="container">
<!-- 地图容器 -->
<view id="mapContainer"></view>
<!-- 控制台输出调试信息 -->
<text>{{ logMessage }}</text>
</view>
</template>
```
#### 初始化页面样式
为上述容器设定合适的宽高比例以及基础布局属性,保证地图能够正常渲染呈现给用户查看[^4]:
```css
<style scoped>
.container {
width: 100%;
height: calc(100vh - var(--status-bar-height));
}
#mapContainer {
position: relative;
width: 100%;
height: 100%;
}
</style>
```
#### 实现核心逻辑功能
利用 Vue 生命周期钩子 mounted() 方法完成地图初始化工作;同时监听窗口大小变化事件以便自适应调整地图尺寸[^1]。
```javascript
<script>
export default {
data() {
return {
mapInstance: null,
logMessage: ''
};
},
methods: {
initMap() {
const tdtKey = process.env.TDT_KEY;
window._AMapSecurityConfig = { securityJsCode: tdtKey };
this.$nextTick(() => {
L.mapquest.key = tdtKey;
let mapOptions = {
center: [39.904, 116.407],
zoom: 12
};
this.mapInstance = L.map('mapContainer', mapOptions);
L.tileLayer(
'http://{s}.tianditu.gov.cn/DataServer?T=vec_w&X={x}&Y={y}&L={z}',
{
attribution:
'© <a href="https://www.tianditu.gov.cn">Tianditu</a>',
subdomains: ['t0', 't1', 't2', 't3', 't4']
}).addTo(this.mapInstance);
console.log('Map initialized successfully.');
this.logMessage = '成功加载';
});
},
handleResize() {
if (this.mapInstance !== null && typeof this.mapInstance.invalidateSize === 'function') {
this.mapInstance.invalidateSize();
}
}
},
mounted() {
this.initMap();
window.addEventListener('resize', this.handleResize);
// 清除不必要的监听器防止内存泄漏
this.$once('hook:beforeDestroy', () => {
window.removeEventListener('resize', this.handleResize);
if (typeof this.mapInstance?.remove === 'function') {
this.mapInstance.remove();
}
});
}
};
</script>
```
阅读全文
相关推荐


















