在uniapp中使用Leaflet加载天地图,可以通过集成Leaflet插件和天地图的方式实现。以下是一个简单的示例代码:
- 首先,确保你的项目中已经安装了Leaflet。如果没有安装,可以通过npm安装:
npm install leaflet- 在pages.json中配置"web-view",允许在App端使用网页组件:
{
  "pages": [
    {
      "path": "pages/index/index",
      "style": {
        "navigationBarTitleText": "首页",
        "enableWebview": true
      }
    }
  ]
}- 在页面的.vue文件中,引入Leaflet和天地图,并初始化地图:
<template>
  <view class="content">
    <web-view src="/hybrid/leaflet-map.html"></web-view>
  </view>
</template>
<script>
export default {
  data() {
    return {};
  },
  onReady() {
    // 初始化Leaflet地图
    this.initMap();
  },
  methods: {
    initMap() {
      const map = L.map('map').setView([39.916527, 116.397128], 12); // 设置中心点和缩放级别
 
      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
      }).addTo(map);
 
      // 加载天地图
      const tdtLayer = L.tileLayer('https://{s}.tianditu.gov.cn/vec_c/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=vec&tileMatrixSet=c&TileMatrix={z}&TileRow={y}&TileCol={x}&style=default&format=tiles&tk=你的天地图key').addTo(map);
 
      // 设置最大和最小缩放级别
      tdtLayer.setMaxZoom(18);
      tdtLayer.setMinZoom(1);
    }
  }
};
</script>- 在static目录下创建leaflet-map.html文件,并在其中初始化Leaflet:
<!DOCTYPE html>
<html>
<head>
  <title>Leaflet Map</title>
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
  <style>
    #map {
      height: 100%;
      width: 100%;
    }
  </style>
</head>
<body>
  <div id="map"></div>
  <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
  <script>
    var map = L.map('map').setView([39.916527, 116.397128], 12);
 
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);
 
    // 加载天地图
    var tdtLayer = L.tileLayer('https://{s}.tianditu.gov.cn/vec_c/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=vec