Raster maps in OpenLayers

Raster map tiles are actually nothing else than raster images. Zoomable raster maps consist of many raster map tiles (in the .png or .jpg format) placed next to each other, ordered in a pyramid scheme. This clever trick allows you to browse just a small part of the map without loading it whole while maintaining a feeling of exploring a single large document. Read more about zoomable maps and the pyramid scheme in this article.

To use MapTiler maps you need an API KEY. Your MapTiler API KEY is on your MapTiler Cloud account page or Get your FREE API key here.

Use recommended 512x512 raster tiles with TileJSON or XYZ.

Next we will explain two ways how to create a map in OpenLayers using your MapTiler maps.

The first way is to use the TileJSON source function; this function is in charge of interpreting the TileJson file and creating the source with all the options and metadata. In a second way we have to use the XYZ source; in this case, we must indicate the URL of the tiles that we want to load in our map and we will not have any metadata associated with the source.

Raster tiles TileJSON

Raster tiles TileJSON are loaded with ol.source.TileJSON function. Start your code with following starter:

Use 256x256 raster tiles for compatibility with certain libraries. To use the 256px tiles you must use this URL in your layer


  https://api.maptiler.com/maps/streets/256/tiles.json?key=YOUR_MAPTILER_API_KEY_HERE

Example of 256x256 raster tiles


const source = new ol.source.TileJSON({
  url: `https://api.maptiler.com/maps/streets/256/tiles.json?key=${key}`,
  crossOrigin: 'anonymous'
});

Raster tiles XYZ (Mercator XYZ)

Raster tiles (Mercator XYZ) are loaded with ol.source.XYZ function. Start your code with following starter:

Use 256x256 raster tiles for compatibility with certain libraries. To use the 256px tiles you must use this URL in your layer


  https://api.maptiler.com/maps/streets/256/{z}/{x}/{y}.png?key=YOUR_MAPTILER_API_KEY_HERE

Example of 256x256 raster tiles


const source = new ol.source.XYZ({
  url: `https://api.maptiler.com/maps/streets/256/{z}/{x}/{y}.png?key=${key}`,
  crossOrigin: 'anonymous'
});

Summary

The two ways of working with raster layers are very similar, the advantages of using TileJson (recommended option) is that we have more information associated with the data source (metadata) and if the service provider changes any metadata our application will always be synchronized and working.