高德爬取瓦片和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)
相关推荐
崔庆才丨静觅6 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60616 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了7 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅7 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅7 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅7 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment7 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅8 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊8 小时前
jwt介绍
前端
爱敲代码的小鱼8 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax