Map setup
Edit your index.html
so we're ready to render a full page map:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>OpenLayers</title>
<style>
@import "node_modules/ol/ol.css";
</style>
<style>
html, body, #map-container {
margin: 0;
height: 100%;
width: 100%;
font-family: sans-serif;
}
</style>
</head>
<body>
<div id="map-container"></div>
<script src="./main.js" type="module"></script>
</body>
</html>
Clear out your main.js
and add the following imports:
import Map from 'ol/Map.js';
import TileLayer from 'ol/layer/WebGLTile.js';
import View from 'ol/View.js';
import XYZ from 'ol/source/XYZ.js';
import {fromLonLat} from 'ol/proj.js';
In this section, we'll be using tiles from MapTiler. If you don't have an account already, you can sign up for a free one and use your key in these examples. After signing up for an account, find your default API key, and add it to main.js
:
const key = '<your-default-api-key>';
To verify that everything works, we'll create a map with a single layer using your API key.
const attributions =
'<a href="https://www.maptiler.com/copyright/" target="_blank">© MapTiler</a> ' +
'<a href="https://www.openstreetmap.org/copyright" target="_blank">© OpenStreetMap contributors</a>';
new Map({
target: 'map-container',
layers: [
new TileLayer({
source: new XYZ({
url: 'https://api.maptiler.com/maps/streets/{z}/{x}/{y}.png?key=' + key,
attributions: attributions,
crossOrigin: 'anonymous',
tileSize: 512,
}),
}),
],
view: new View({
center: fromLonLat([-58.3816, -34.6037]),
zoom: 11,
}),
});