You will learn how a basic Raster Map with OpenLayers is implemented. We will display a OpenLayers raster map with minimal configuration effort. This tutorial illustrates the use of the PTV Developer Raster Maps API.
Prerequisites
- Basic knowledge of JavaScript.
- Helpful: Basic knowledge of OpenLayers.
Getting started
- Read up on the PTV Developer Raster Maps API
- Request an API key:
- Register and login at myptv.com
- Activate PTV Developer
- Create your API key
Create an HTML page
Create an HTML file called index.html
and load the OpenLayers packages as seen below.
<html lang="en">
<head>
<title>PTV Raster Map OpenLayers Tutorial</title>
<link rel="stylesheet" href="https://unpkg.com/openlayers@4.6.5/dist/ol.css"/>
<style>
body,
html {
border: 0;
padding: 0;
margin: 0;
}
#map {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script type="text/javascript" src="https://unpkg.com/openlayers@4.6.5/dist/ol.js"></script>
<script type="text/javascript">
// The JS code below goes here
</script>
</body>
</html>
We also add some styling to fill the screen and a <div>
with id "map" to the HTML body, which will contain the OpenLayers map.
Initialize the OpenLayers map
Now let's initialize a OpenLayers map in the <div>
element:
// Karlsruhe
const view = new ol.View({
center: ol.proj.fromLonLat([8.4, 49]),
zoom: 13
});
const map = new ol.Map({
target: "map",
view
});
We have set the initial coordinates to Karlsruhe, of course you can choose any other coordinates. All you see for now is a gray screen with zoom control in the top left and the attribution control in the bottom right. Let's change that by adding a tile layer!
Add a Tile Layer
Let's add a tile layer that uses the PTV Raster Map API:
// Please enter your API key here
const API_KEY = "YOUR_API_KEY";
const tileURL = `https://api.myptv.com/rastermaps/v1/image-tiles/{z}/{x}/{y}?apiKey=${API_KEY}`;
const ptvTileLayer = new ol.layer.Tile({
source: new ol.source.XYZ({
url: tileURL,
layer: "ptv-raster",
maxZoom: 22,
attributions: "©2023, PTV Group, HERE"
})
});
// ...
const map = new ol.Map({
target: "map",
layers: [ptvTileLayer],
view
});
We add the ptvTileLayer
to the layers list of the map
we created in the step above and pass it the PTV Raster Map image tile URL with our API key. That's all it takes to make the map appear in your web page!
There are many things you can do with your raster map. Check out the features of the PTV Developer Raster Maps API and the OpenLayers Examples!