高德爬取瓦片和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)
相关推荐
Dontla16 分钟前
黑马node.js教程(nodejs教程)——AJAX-Day01-04.案例_地区查询——查询某个省某个城市所有地区(代码示例)
前端·ajax·node.js
威哥爱编程18 分钟前
vue2和vue3的响应式原理有何不同?
前端·vue.js
呆呆的猫21 分钟前
【前端】Vue3 + AntdVue + Ts + Vite4 + pnpm + Pinia 实战
前端
qq_4560016523 分钟前
30、Vuex 为啥可以进行缓存处理
前端
浪裡遊44 分钟前
Nginx快速上手
运维·前端·后端·nginx
天生我材必有用_吴用1 小时前
Vue3后台管理项目封装一个功能完善的图标icon选择器Vue组件动态加载icon文件下的svg图标文件
前端
小p1 小时前
初探typescript装饰器在一些场景中的应用
前端·typescript·nestjs
晓得迷路了1 小时前
栗子前端技术周刊第 72 期 - 快 10 倍的 TypeScript、React Router 7.3、Astro 5.5...
前端·javascript·typescript
xiaoyan20151 小时前
vue3仿Deepseek/ChatGPT流式聊天AI界面,对接deepseek/OpenAI API
前端·vue.js·deepseek
加个鸡腿儿1 小时前
D老师:如何正确控制图片尺寸?父容器设置为何失效?
前端·css