uniapp 如何在项目中使用天地图

在 uniapp 项目中如何集成天地图?需要引入哪些 SDK 或者插件?有没有具体的配置步骤和示例代码?另外,天地图在 uniapp 中是否支持 H5 和原生 App 端都使用?

2 回复

在UniApp中使用天地图,步骤如下:

  1. 申请天地图密钥:前往天地图官网注册并获取API密钥(Key)。

  2. 引入地图组件:在pages.json中配置需要地图的页面,启用map组件。

  3. 页面中使用地图:在Vue文件的<template>中添加<map>标签,设置latitudelongitude等属性。

  4. 加载天地图:通过tiles属性指定瓦片图地址,例如:

    <map :tiles="[{
      url: 'https://t{0-7}.tianditu.gov.cn/vec_w/wmts?tk=你的密钥',
      type: 'grid'
    }]">
    </map>
    

    注意替换你的密钥为实际Key。

  5. 调整样式与交互:根据需求设置缩放、标记点等属性。

注意:需确保域名tianditu.gov.cn在UniApp合法域名列表中,或开启调试模式跳过校验。


在 UniApp 中使用天地图(Tianditu)主要通过 WebView 组件或 JavaScript API 实现。以下是具体步骤和示例代码:

方法一:使用 WebView 组件加载天地图网页

  1. 申请天地图 API 密钥:访问天地图官网注册并获取密钥(Key)。
  2. 创建 HTML 文件:在 UniApp 项目的 static 目录下新建一个 HTML 文件(如 map.html),嵌入天地图 JavaScript API。
  3. 通过 WebView 加载:在页面中使用 <web-view> 组件引用该 HTML 文件。

示例代码

  1. static/map.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>天地图</title>
    <script src="https://api.tianditu.gov.cn/api?v=4.0&tk=您的密钥"></script>
    <style>
        #map { width: 100%; height: 100vh; }
    </style>
</head>
<body>
    <div id="map"></div>
    <script>
        var map = new T.Map("map");
        map.centerAndZoom(new T.LngLat(116.397, 39.908), 12); // 设置中心点和缩放级别
    </script>
</body>
</html>
  1. UniApp 页面
<template>
    <view>
        <web-view src="/static/map.html"></web-view>
    </view>
</template>

方法二:通过 JavaScript API 在 UniApp 中直接集成(需处理跨平台兼容性)

  1. 在页面中引入天地图 API:
<template>
    <view>
        <div id="mapContainer" style="width:100%; height:100vh;"></div>
    </view>
</template>

<script>
export default {
    mounted() {
        // 动态加载天地图 API(确保在 H5 环境)
        if (typeof window !== 'undefined') {
            const script = document.createElement('script');
            script.src = 'https://api.tianditu.gov.cn/api?v=4.0&tk=您的密钥';
            script.onload = this.initMap;
            document.head.appendChild(script);
        }
    },
    methods: {
        initMap() {
            const map = new T.Map('mapContainer');
            map.centerAndZoom(new T.LngLat(116.397, 39.908), 12);
        }
    }
}
</script>

注意事项:

  • 密钥替换:将代码中的 您的密钥 替换为实际申请的天地图 Key。
  • 平台限制:WebView 和 JavaScript API 主要适用于 H5 平台;在 App 端需使用 <web-view> 或原生地图插件(如高德/百度地图插件)。
  • 跨域问题:确保天地图 API 在 H5 中可正常加载,必要时配置域名白名单。

通过以上方法,即可在 UniApp 项目中集成天地图功能。根据需求选择合适的方式,并注意平台兼容性。

回到顶部