通过 Leaflet 使用本地图块的 HTML 离线地图

2022-01-12 00:00:00 offline leaflet tiles html maps

有没有办法使用 HTML 和 JavaScript 完全离线显示给定区域的地图?我正在寻找一种适合移动设备(阅读支持 Cordova)的解决方案.

Is there a way to display a map for a given area completely offline using HTML and JavaScript? I am looking for a mobile-friendly (read Cordova-enabled) solution.

推荐答案

在 这篇博文.我已经从中编译了一个完整的代码示例.步骤如下:

There is an elegant solution for this problem in this blog post. I have compiled a full code example from it. Here are the steps:

1.创建地图图块

  • 下载Mobile Atlas Creator
  • 创建一个具有 OSMdroid ZIP 格式的新图集
  • 进行地图和缩放选择,将您的选择添加到地图集
  • 点击创建图集"
  • 解压图集文件
  • 您的图块具有以下格式:{atlas_name}/{z}/{x}/{y}.png({z} 代表缩放")
  • download Mobile Atlas Creator
  • create a new atlas with OSMdroid ZIP format
  • make map and zoom selection, add your selection to the atlas
  • click "Create atlas"
  • unzip the atlas file
  • your tiles have this format: {atlas_name}/{z}/{x}/{y}.png ({z} stands for "zoom")

<强>2.设置 HTML 和 JavaScript

  • 将 atlas 文件夹复制到 HTML 根目录
  • 下载leaflet.js和leaflet.css并复制到html根目录
  • 使用以下代码创建 index.html
    • 调整起始坐标并在 var mymap 定义的行上缩放
    • 将 atlasName 更改为您的文件夹名称,设置所需的 maxZoom
    • copy your atlas folder to your HTML root
    • download leaflet.js and leaflet.css and copy them to html root
    • create index.html with the code below
      • adjust starting coordinates and zoom on the line where var mymap is defined
      • change atlasName to your folder name, set your desired maxZoom

      3.你都准备好了!享受吧!

      • 在浏览器中运行 index.html

      <!DOCTYPE html> 
      <html> 
      	<head> 
      		<title>Leaflet offline map</title>
      		<link rel="stylesheet" charset="utf-8" href="leaflet.css" />
      	<script type="text/javascript" charset="utf-8" src="leaflet.js"></script>
      		<script>
      			function onLoad() {
      
      				var mymap = L.map('mapid').setView([50.08748, 14.42132], 16);
      
      				L.tileLayer('atlasName/{z}/{x}/{y}.png',
      				{    maxZoom: 16  }).addTo(mymap);
      			}
      		</script>	
      	</head>
      	<body onload="onLoad();"> 
      		<div id="mapid" style="height: 500px;"></div>
      	</body>
      </html>

相关文章