HTML offline map with local tiles via Leaflet

Kozuch picture Kozuch · Apr 25, 2017 · Viewed 24k times · Source

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.

Answer

Kozuch picture Kozuch · Apr 25, 2017

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. Create map tiles

  • 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. Set up HTML and JavaScript

  • 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. You are all set! Enjoy!

  • run index.html in your browser

<!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>