高德爬取瓦片和vue2使用

1、渲染瓦片地址

javascript 复制代码
<template>
  <div class="command-center">
    <div id="mapContainer" ref="map" class="mapContainer"/>
  </div>
</template>

<script>
import Vue from 'vue'
import L from 'leaflet'
export default {
  data() {
    return {
      zoom: 7,
      center: [24.00000, 101.000000],
      markerGroup: null,
      boundaryGroup: null,
    }
  },
  mounted() {
    this.initMap()
  },
  beforeDestroy() {
  },
  methods: {
    initMap() {
      this.map = L.map(this.$refs.map, {
        attributionControl: false,
        zoomControl: false
      })
      this.map.setView(this.center, this.zoom)
      //内网瓦片地址
      let url = 'http://127.0.0.1:5000/tiles/{z}/{x}/{y}.png'
      this.$L.tileLayer(url, {
        minZoom: 7,
        maxZoom: 12
      }).addTo(this.map)
      this.markerGroup = this.$L.layerGroup().addTo(this.map)
      this.boundaryGroup = this.$L.layerGroup().addTo(this.map)
      // 监听地图缩放级别
      this.map.on('zoom', this.mapZoom)
      // 绘制点
      this.inputMarkers()
      //初始化地图描边
      this.miaobian()
    },
    miaobian() {
      // yunnan 是地图json,里面包含了边界经纬度
      const boundary = yunnan.features[0].geometry.coordinates[0][0].map(item => item.reverse())
      const boundaryLayer = this.$L.polygon(boundary, {
        color: '#366ef4',
        weight: 4,
        fillColor: '#ffffff00',
        fillOpacity: 0
      })
      this.boundaryGroup.addLayer(boundaryLayer)
    },
    // 监听地图缩放
    mapZoom() {
      this.zoom = this.map.getZoom()
    },
    // 构建地图标记
    async inputMarkers() {
      //this.stations是地图标记数据
      this.stations.forEach(item => {
        const marker = this.$L.marker([item.lat, item.lng], {
          icon: this.$L.icon({
            iconUrl: require('../assets/图标.png'),
            iconSize: [50, 50],
            iconAnchor: [25, 50], // 图标锚点(默认在左下角)
            popupAnchor: [0, -50]
          })
        })
        marker.bindTooltip(item.name, {
          permanent: true,
          className: 'marker-label'
        })
        marker.on('click', (event) => {
          this.stationMarkerClick(event, item, marker)
        })
        this.markerGroup.addLayer(marker)
      })
    },
    // 点击事件
    async stationMarkerClick(event, data, marker) {

    },
    // 获取电站列表
    async requestList() {
      try {
        const params = {}
        if (this.currentArea) {
          params.city = this.currentArea.name
          if (this.stationListAll && this.stationListAll.length > 0) {
            //直接遍历
            let stationList = [];
            for (var i = 0; i < this.stationListAll.length; i++) {
              if (this.stationListAll[i].city == params.city) {
                stationList.push(this.stationListAll[i]);
              }
            }
            this.stationList = stationList
          } else {
            const res = await selectYnsxsdDianzhanInfo(params);
            this.stationList = res.data || []
          }
        } else {
          const res = await selectYnsxsdDianzhanInfo(params);
          this.stationList = res.data || [];
          this.stationListAll = JSON.parse(JSON.stringify(res.data));//防止引用
        }
      } catch (err) {
        this.$message.error(err.toString() )
        console.log(err)
      }
    },
  }
}
</script>

<style lang="scss" scoped>
</style>

1、瓦片抓取和配置

使用python 检测,存在则从文件夹获取,不存在则从网络下载。

如果本地部署则访问地址为 http://127.0.0.1:5000/tiles/1/1/1.png

第一次可以先抓取再进行部署到nginx内网

python 复制代码
import os
import requests
from flask import Flask, request, Response

app = Flask(__name__)

# 定义tiles文件夹路径
TILES_DIR = os.path.join(os.path.dirname(__file__), 'tiles')


@app.route('/tiles/<int:z>/<int:x>/<int:y>.png', methods=['GET'])
def get_tile(z, x, y):
    # 构造本地图片路径
    tile_path = os.path.join(TILES_DIR, str(z), str(x), f"{y}.png")

    # 如果图片存在,直接读取并返回
    if os.path.exists(tile_path):
        print('图片存在,直接读取并返回')
        with open(tile_path, 'rb') as f:
            return Response(f.read(), content_type='image/png')

    # 如果图片不存在,从URL下载并保存
    print('图片不存在,从URL下载并保存')
    print(tile_path)
    data = fetch_data(x, y, z)
    if isinstance(data, bytes):
        # 确保文件夹存在
        os.makedirs(os.path.dirname(tile_path), exist_ok=True)
        # 保存图片到本地
        with open(tile_path, 'wb') as f:
            f.write(data)
        return Response(data, content_type='image/png')
    else:
        return data


def fetch_data(x, y, z):
    url = f'https://webrd04.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}'
    response = requests.get(url)
    if response.status_code == 200:
        return response.content
    else:
        return f"请求失败,状态码: {response.status_code}"


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
相关推荐
且白12 分钟前
vsCode使用本地低版本node启动配置文件
前端·vue.js·vscode·编辑器
程序研13 分钟前
一、ES6-let声明变量【解刨分析最详细】
前端·javascript·es6
疯狂的沙粒34 分钟前
在uni-app中如何从Options API迁移到Composition API?
javascript·vue.js·uni-app
siwangqishiq238 分钟前
Vulkan Tutorial 教程翻译(四) 绘制三角形 2.2 呈现
前端
李三岁_foucsli40 分钟前
js中消息队列和事件循环到底是怎么个事,宏任务和微任务还存在吗?
前端·chrome
尽欢i40 分钟前
HTML5 拖放 API
前端·html
xiaominlaopodaren1 小时前
Three.js 光影魔法:如何单独点亮你的3D模型
javascript
PasserbyX1 小时前
一句话解释JS链式调用
前端·javascript
1024小神1 小时前
tauri项目,如何在rust端读取电脑环境变量
前端·javascript
Nano1 小时前
前端适配方案深度解析:从响应式到自适应设计
前端