Leaflet detect retina/HiDPI display
This tutorial shows how to detect a retina/HiDPI display to utilize the high resolution in the map images using Leaflet JS.
Using the detectRetina in the tileLayer options if the user is on a retina display, it will request four tiles of half the specified size and a bigger zoom level in place of one to utilize the high resolution.
You can also use the scale parameter(@2x) in the tileLayer url to get the “retina”/HiDPI images directly from the server regardless of the device resolution. For example: https://api.maptiler.com/maps/satellite-v4/{z}/{x}/{y}@2x.jpg.
NPM module setup
npm install --save leaflet
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
const key = 'YOUR_MAPTILER_API_KEY_HERE';
const map = L.map('map').setView([45.43725,10.69844], 14.84);
const layer = L.tileLayer(`https://api.maptiler.com/maps/satellite-v4/{z}/{x}/{y}.png?key=${key}`,{
tileSize: 512,
zoomOffset: -1,
minZoom: 1,
attribution: "\u003ca href=\"https://www.maptiler.com/copyright/\" target=\"_blank\"\u003e\u0026copy; MapTiler\u003c/a\u003e \u003ca href=\"https://www.openstreetmap.org/copyright\" target=\"_blank\"\u003e\u0026copy; OpenStreetMap contributors\u003c/a\u003e",
crossOrigin: true,
detectRetina: true,
}).addTo(map);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex">
<title>Leaflet detect retina/HiDPI display | NPM example</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div id="map"></div>
<script type="module" src="./main.js"></script>
</body>
</html>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
Replace YOUR_MAPTILER_API_KEY_HERE with your own API key. Make sure to secure the key before you publish it.
Learn more
Example using the scale parameter in the tileLayer url.
const myLayer = L.tileLayer(
`https://api.maptiler.com/maps/satellite-v4/{z}/{x}/{y}@2x.jpg?key=${key}`,
{
tileSize: 512,
zoomOffset: -1,
minZoom: 1,
attribution:
'\u003ca href="https://www.maptiler.com/copyright/" target="_blank"\u003e\u0026copy; MapTiler\u003c/a\u003e \u003ca href="https://www.openstreetmap.org/copyright" target="_blank"\u003e\u0026copy; OpenStreetMap contributors\u003c/a\u003e',
crossOrigin: true,
},
).addTo(map);