Embed JavaScript Map for Free Using MapLibre

Introduction

In addition to Google Map API, MapLibre GL JS is an open-source library for publishing maps on our websites. The maps are usually in the vector format and fast rendering in browser has become possible thanks to GPU.

In my previous blog post “Embed Google Map for Free”, I have discussed how to embed a static Google Map on our website for free. However, embedding a dynamic map using JavaScript requires using Google Map API and Google Map API is not free.

In this blog post, I would like to discuss how to use MapLibre to create custom dynamic maps on our websites using JavaScript mostly for free.

MapLibre GL JS

Quick Start

Add a marker to a Map could be just as simple as the follows. Because the vectorized map is hosted on MapTiler, we would have to register an account, create an API key, and use the API key in the code. Fortunately, there is free plan available and there are a decent number of free requests given to the user.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Add a default marker</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<script src="https://unpkg.com/maplibre-gl@2.4.0/dist/maplibre-gl.js"></script>
<link href="https://unpkg.com/maplibre-gl@2.4.0/dist/maplibre-gl.css" rel="stylesheet" />
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<div id="map"></div>

<script>
var map = new maplibregl.Map({
container: 'map',
style:
'https://api.maptiler.com/maps/streets/style.json?key=YOUR_OWN_MAPTILER_API',
center: [12.550343, 55.665957],
zoom: 8
});

var marker = new maplibregl.Marker()
.setLngLat([12.550343, 55.665957])
.addTo(map);
</script>

</body>
</html>

The API keys can be abused by other users, because the API key is inside the HTML code. It is highly recommended using one key per web application and set allowed HTTP origins to prevent stealing of the key.

Finally, to make the embedded map compatible with the existing webpage, we used iframe for integration.

1
2
3
<div style="overflow-x:auto;">
<iframe src="/javascript/maplibre/add-default-marker.html" style="width:100%; height:512px", title="add-default-marker"></iframe>
</div>

The embedded map for this example looks like this.

Custom Example

Similar to the map of places that I have visited recently in my previous blog post “Embed Google Map for Free”, I created another one using MapLibre GL JS.

Miscellaneous

The free street map style from MapTiler lacks details comparing to Google Map. However, MapTiler allows the user to custom different map styles for different advanced purposes, which is something that Google Map could not do.

References

Author

Lei Mao

Posted on

10-09-2022

Updated on

10-09-2022

Licensed under


Comments