Adding an interactive map to your website
new york map

Adding an interactive map to your website

By Quaro | the dev diary | 15 Feb 2020


Introduction

Hi,

I'm a web developer and I create G.I.S. (geographic information system) web applications. This mostly involves creating maps that show different kind of data on them.

Nowadays, maps are common on a lot of websites, from restaurants web pages to social media, and they're often powered by Google. Sometimes this can be annoying, since you need an API key and maybe you would like some more freedom in your map behaviour. In this post I will show you that it's not so difficult to add a custom map to your website.

An open source solution 

Since I work for a research institute, we're interested in open source software and we try to use it as much as we can. That's why the solution I will show here uses two open source components:

Openlayers (https://openlayers.org/), a javascript library that takes care of showing and controlling your map, and

OpenStreetMap (https://www.openstreetmap.org/) a free map of the world that also offers different tile servers (these are servers that create .png images (tiles) from a vector representation of the planet, and serve them to your page.

The first step is downloading the latest version of OpenLayers from their download page (https://openlayers.org/download/)

ol download

for our purpose, you can download the package -dist, which only includes the build and CSS needed to run. In case you want to experiment more, there's another package with docs and examples.

The project

Next, I created a static web project in Eclipse (my choice of IDE, another great open source solution - https://www.eclipse.org/), and copied the downloaded directory called v.6.2.1-dist inside the WebContent folder:

proj

 I also created a js folder for my javascript files, and a home.html with some fake text in it:


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Map Example</title>
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ac condimentum felis. Maecenas eu sapien in est rutrum tincidunt. Mauris aliquet
nulla nec volutpat pharetra. Nunc orci quam, accumsan sed arcu ac, mollis lobortis risus. Cras varius ut dolor at interdum. Nulla facilisi. Nam nec
turpis non erat placerat maximus. Praesent feugiat cursus justo at eleifend. Donec vel diam eget eros sodales malesuada. Cras non nulla eu odio
scelerisque laoreet vitae non libero.</p>
<p>Etiam congue velit id dui pulvinar vestibulum. Duis aliquet, erat vel tempus aliquam, elit ipsum aliquam ex, at finibus ante ante vitae magna.
Aliquam in orci massa. Etiam sollicitudin elementum euismod. Nullam magna ligula, cursus vel arcu sed, interdum ullamcorper est. Duis vestibulum,
urna et vehicula vulputate, ipsum turpis pulvinar ex, sed sagittis mauris magna volutpat risus. Orci varius natoque penatibus et magnis dis
parturient montes, nascetur ridiculus mus. Ut lectus nunc, venenatis non faucibus eget, tristique a diam.</p>
</body>
</html>

Let's add all the references we need in the <head> section:

<link rel="stylesheet" href="v6.2.1-dist/ol.css" type="text/css" />
<script src="v6.2.1-dist/ol.js"></script>
<script src="js/map.js"></script>

The first line adds the CSS for OpenLayers, the second one is a reference to the actual library, and the third one links the javascript file we're going to create to show the map.

Let's say we want to add the map between the first and the second paragraph of our page; all we need is a div with an id of our choice, I'll call it map, because I have no imagination:

<div id="map"></div>

And I'm adding some style to it:

<style>
#map {
width: 500px;
height: 300px;
border: 1px solid black;
}
</style>

Great, most of the work is done already!

Adding the Javascript function

It's time to create that map.js we linked before, and inside of it we only need one function:

window.onload = function(e) {

};

This function is automatically executed when the page finishes loading; I know there's some debate around it and how the using of a specific jquery function is usually preferred, but it will work for demonstration purposes.

In the body of the function, we need to do two things:

Creating a layer: our map will only have one layer, the base one that shows the OpenStreetMap layer, and it's created like this:

var baseLayer = new ol.layer.Tile({
source : new ol.source.OSM({
url : "https://a.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png",
crossOrigin : null
}),
name : 'Base layer'
});

An OpenLayers layer is composed of a source (the origin of our data), and in this case it's a URL to an OpenStreetMap server (I use the german one, but you can experiment with others). The crossOrigin option is used to disable the ssl that would give a CORS error when trying to retrieve the tiles.

The only other option we need for now is the layer name.

Now that we have a valid base layer, all we have to do is creating a map and adding it:

olMap = new ol.Map({
layers : [ baseLayer ],
target : 'map',
view : new ol.View({
center : [-8230343.1831012275, 4954430.105644477],
zoom : 8
})
});

The map has three attributes:

layers: here we can add all the layers we want to put in the map, as an array.
target: the id of the div where the map will be displayed.
view: the view is another OpenLayers object that tells where to zoom on the map; you can add multiple parameters to it but for now we can just pass the center of the map (I used New York coordinates, in the same projection system used by Google Maps, or EPSG: 3857 in case you're interested), and the initial zoom level.

The result

res

This the final result; the map has full pan and zoom functions, built-in zoom +/- buttons, and full touch capabilities. Not bad for a bunch of lines of code!

Conclusions

I hope you'll find this information useful for your projects; sometimes adding interactive content seems harder than it actually is, and nowadays we're lucky enough to have powerful libraries that make our job a bit simpler.

In the next post I will talk more about layers, and adding custom content to the map we just created.


Quaro
Quaro

web / gis developer and freelance illustrator


the dev diary
the dev diary

Discussion, challenges and solutions for web developers

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.