Raster tiles in OpenLayers
Raster tiles maps 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 the feeling of exploring a single large document. Read more about zoomable maps and the pyramid scheme in this article.
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 the following starter:
Replace YOUR_MAPTILER_API_KEY_HERE
with your actual MapTiler API key.
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-v2/256/tiles.json?key=${key}`
Example of 256x256 raster tiles
const source = new ol.source.TileJSON({
url: `https://api.maptiler.com/maps/streets-v2/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 the following starter:
Replace YOUR_MAPTILER_API_KEY_HERE
with your actual MapTiler API key.
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-v2/256/{z}/{x}/{y}.png?key=${key}`
Example of 256x256 raster tiles
const source = new ol.source.XYZ({
url: `https://api.maptiler.com/maps/streets-v2/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) are 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.