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);

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);
How to use Leaflet

How to use Leaflet

Tutorials

Create and display Leaflet maps on web pages with MapTiler.

How to display a custom map on a web with Leaflet

Custom Map

Tutorials

Display custom MapTiler maps on web pages with Leaflet JS.

Display a Marker on the map using Leaflet

Display Marker

Tutorials

Add default map markers using Leaflet JS web mapping library.

How to make a map with pins using Leaflet

Make a map with pins

Examples

Create maps with custom pins and markers in Leaflet JS.

Was this helpful?