Skip to content

Instantly share code, notes, and snippets.

@warmspringwinds
Created July 23, 2014 18:52
Show Gist options
  • Save warmspringwinds/4a9fec9783c4a49ae054 to your computer and use it in GitHub Desktop.
Save warmspringwinds/4a9fec9783c4a49ae054 to your computer and use it in GitHub Desktop.
Example of calculating coordinates of visible tiles in Leaflet.js
<html>
<head>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
<link rel="stylesheet" href="main.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<title>Leaflet test page</title>
</head>
<body>
<h1>Leaflet test page</h1>
<div id="map"></div>
<button id="getVisibleTilesBtn" >Write coords of visible tiles to console</button>
<script type="text/javascript">
function getVisibleTilesCoords(map)
{
// get bounds, zoom and tileSize
var bounds = map.getPixelBounds();
var zoom = map.getZoom();
var tileSize = 256;
var tileCoordsContainer = [];
// get NorthWest and SouthEast points
var nwTilePoint = new L.Point(Math.floor(bounds.min.x / tileSize),
Math.floor(bounds.min.y / tileSize));
var seTilePoint = new L.Point(Math.floor(bounds.max.x / tileSize),
Math.floor(bounds.max.y / tileSize));
// get max number of tiles in this zoom level
var max = map.options.crs.scale(zoom) / tileSize;
// enumerate visible tiles
for (var x = nwTilePoint.x; x <= seTilePoint.x; x++)
{
for (var y = nwTilePoint.y; y <= seTilePoint.y; y++)
{
var xTile = Math.abs(x % max);
var yTile = Math.abs(y % max);
tileCoordsContainer.push({ 'x':xTile, 'y':yTile });
console.log('tile ' + xTile + ' ' + yTile);
}
}
return tileCoordsContainer;
};
var map = L.map('map').setView([51.505, -0.09], 13);
var button = document.getElementById('getVisibleTilesBtn');
button.onclick = function()
{
console.log(getVisibleTilesCoords(map));
};
var myLayerObject = L.tileLayer('http://otile1.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.jpg', {}).addTo(map);
</script>
</body>
</html>
#map { height: 180px; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment