How to use OpenLayers
This Step-by-Step tutorial shows how to create an OpenLayers map and display it on a web page using MapTiler Cloud.
By following these steps, you will be able to harness the power of MapTiler Cloud to effortlessly integrate stunning map visuals and functionality into your web applications. Experiment with different map styles, customizations, and functionalities to create an exceptional mapping experience for your web application users.
-
Create a basic HTML file.
-
Include the OpenLayers JavaScript and CSS files in the
<head>
of your HTML file. -
Create a
<div>
element with a certain id where you want your map to be.Add
<div>
tag into your page. This div will be the container where the map will be loaded. -
The div must have non-zero height. Go to the head style section and copy the following lines:
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
-
Finally, load the map with the style. Go back to the body script section and white:
const key = 'YOUR_MAPTILER_API_KEY_HERE'; const source = new ol.source.TileJSON({ url: `https://api.maptiler.com/maps/streets-v2/tiles.json?key=${key}`, tileSize: 512, crossOrigin: 'anonymous' }); const map = new ol.Map({ layers: [ new ol.layer.Tile({ source: source }) ], target: 'map', view: new ol.View({ constrainResolution: true, center: ol.proj.fromLonLat([16.62662018, 49.2125578]), zoom: 14 }) });
-
Replace
YOUR_MAPTILER_API_KEY_HERE
with your actual MapTiler API key. -
Create an attribution control that is not collapsible so that it is always visible.
const key = 'YOUR_MAPTILER_API_KEY_HERE'; const source = new ol.source.TileJSON({ url: `https://api.maptiler.com/maps/streets-v2/tiles.json?key=${key}`, tileSize: 512, crossOrigin: 'anonymous' }); const attribution = new ol.control.Attribution({ collapsible: false, }); const map = new ol.Map({ layers: [ new ol.layer.Tile({ source: source }) ], target: 'map', view: new ol.View({ constrainResolution: true, center: ol.proj.fromLonLat([16.62662018, 49.2125578]), zoom: 14 }) });
-
Add the new attribution control to the map. We will modify the default controls on the map so that the attribution is always visible using the non-collapsible attribution control.
const map = new ol.Map({ layers: [ new ol.layer.Tile({ source: source }) ], controls: ol.control.defaults.defaults({attribution: false}).extend([attribution]), target: 'map', view: new ol.View({ constrainResolution: true, center: ol.proj.fromLonLat([16.62662018, 49.2125578]), zoom: 14 }) });
Learn more
There are two ways to use MapTiler maps in OpenLayers:
If you do not know the difference between Raster and Vector or you have doubts about which format is better for you, consult the article Raster vs Vector Map Tiles: What Is the Difference Between the Two Data Types?