Create map viewer with OpenLayers
Creating a basic map viewer is very straightforward using MapTiler Cloud. You can find code examples in your account. Just go to MapTiler Cloud, log in or create your free account. Then choose any of the map styles, for example, Streets, and click on OpenLayer in Vector or Raster Tiles section. In the following examples, we will work with Vector Tiles.
The code example in MapTiler Cloud has these elements:
In the header of an HTML document is loaded the OpenLayers library
and ol-mapbox-style plugin for vector tiles
In the body section, it has
<div> element which loads your map from the following script.
This line creates an OpenLayers
The following line adds MapTiler API for your map, a unique key is already included.
Don’t forget to protect your map key if you publish your map.
ol.View specify the center, resolution, and zoom level of the map
The following line will load your map style.
This all together makes a basic map viewer for maps hosted via MapTiler Cloud. Open Layers gives you variability of functions that can be added to the map. Below is described how to add a point, circle, popup, and GeoJSON.
How to add a point on the map
This snippet code will create a new vector point named point at Venice. Don’t forget to add this point to your map as a new layer using
How to add Circle
For adding Circle we have to start with setting up its parameters.
The next step is to add a new layer with a circle and define its style.
zIndex determines the order of layers.
Again don’t forget to load the circle to your map as a new layer using
How to add Pop-up on the map
For adding a popup, you have to create a new
<div id="popup"> element right after the
<div id="map"> element.
By adding the following code snippet in the
<script> section, initialize the popup. Our popup will open when you click on any place on the map and the popup will show the text “Hello world! I am popup”
To set the style of popup add this part into the
<style> section in the
<head> of our HTML document and choose properties of your popup. We set a white background with shadows around
How to add GeoJSON
Adding GeoJSON to the map will be demonstrated on datasets visualizing subway stations and lines in New York.
You can host your dataset via MapTiler Cloud as we did. Upload easily a GeoJSON file or create a new dataset from the Scratch using Vector Data Editor.
To add a new layer with your dataset add this code to the
<script> in the body of your HTML document. In the URL section, we included datasets.
Dataset showing stations will be displayed over dataset showing line. This is set with zIndex, a higher number means a higher layer.
map.addLayer(SubwLines) at the end of the script for loading them as layers.