服务端的转发服务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
const express = require('express'); const axios = require('axios'); const cors = require('cors'); const app = express(); const port = 3000; // 使用 cors 中间件 app.use(cors()); app.get('/tiles/:z/:x/:y', async (req, res) => { const { z, x, y } = req.params; const googleTileUrl = `https://mt1.google.com/vt/lyrs=s&x=${x}&y=${y}&z=${z}`; try { const response = await axios.get(googleTileUrl, { responseType: 'arraybuffer' }); res.set('Content-Type', 'image/png'); res.send(response.data); } catch (error) { console.error(error); res.status(500).send('Error fetching tile'); } }); app.listen(port, () => { console.log(`Tile proxy server running at http://localhost:${port}`); }); |
网页端的加载服务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
<!DOCTYPE html> <html> <head> <title>Leaflet Google Satellite Tiles</title> <link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" /> <script src="https://unpkg.com/leaflet/dist/leaflet.js"></script> <script src="https://unpkg.com/leaflet-image/leaflet-image.js"></script> </head> <body> <div id="map" style="height: 80vh; width: 100vw;"></div> <button id="screenshotButton">Take Screenshot</button> <script> const map = L.map('map').setView([ 39.9042, 116.4074 ], 12); var tileLayer = L.tileLayer('http://localhost:3000/tiles/{z}/{x}/{y}', { maxZoom: 18, minZoom: 0, tileSize: 256, detectRetina: true, // 检测视网膜屏幕并加载高分辨率切片 }).addTo(map); // 加载失败 tileLayer.on('tileerror', function(event) { console.log('Tile failed to load:', event); }); // 添加标记 L.marker([34.5823, 105.9126]).addTo(map) .bindPopup('甘肃省天水市麦积区甘泉镇归风村') .openPopup(); // 截图按钮点击事件 document.getElementById('screenshotButton').addEventListener('click', function () { leafletImage(map, function (err, canvas) { if (err) { console.error(err); return; } // 将 Canvas 转换为图片 const img = document.createElement('img'); const dimensions = map.getSize(); img.width = dimensions.x; img.height = dimensions.y; img.src = canvas.toDataURL(); // 创建一个下载链接 const link = document.createElement('a'); link.href = img.src; link.download = 'map-screenshot.png'; link.appendChild(img); // 模拟点击下载链接 link.click(); }); }); </script> </body> </html> |