Skip to content

Instantly share code, notes, and snippets.

@MapTilesAPI
Last active March 24, 2022 20:08
Embed
What would you like to do?
Example and helper script for using the tiles provided by MapTiles API as a LeafletJS TileLayer
<!DOCTYPE html>
<html>
<head>
<title>MapTiles API Leaflet Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js"></script>
<!-- important: copy the maptilesapi.js to your webspace and adjust the src url accordingly. //-->
<script src="maptilesapi.js"></script>
<style type="text/css">
html,body{width:100%;height:100%;padding:0px;}
#mymap{width:100%;height:100%;}
</style>
</head>
<body>
<div id="mymap"></div>
<script type="text/javascript">
var map = L.map('mymap').setView({lon: 2.294694, lat: 48.858093}, 5);
// using the english labeled tiles here
// important: copy the maptilesapi.js to your webspace and replace <YOUR X-RapidAPI-Key> with your X-RapidAPI-Key.
// You can get an api key by signing up and subscribing to a plan at http://www.maptilesapi.com (a free tier for non-commercial use is available)
// important: you have to attribute OpenStreetMap contributors to use the map tiles provided by MapTiles API
L.tileLayer.mapTilesAPI('https://maptiles.p.rapidapi.com/en/map/v1/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '&copy; <a href="https://openstreetmap.org/copyright" target="_blank">OpenStreetMap contributors</a>, @copy; <a href="https://www.maptilesapi.com" target="_blank">MapTiles API</a>'
}).addTo(map);
L.control.scale().addTo(map);
</script>
</body>
</html>
"use strict";
var maptileskey='<INSERT YOUR X-RapidAPI-Key HERE>';
function callAjax(url, callback) {
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback(xmlhttp.response);
}
}
xmlhttp.onloadstart = function(ev) {
xmlhttp.responseType = "blob";
}
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader('X-RapidAPI-Key', maptileskey);
xmlhttp.send();
};
L.TileLayer.MapTilesAPI = L.TileLayer.extend({
initialize: function (url, options) {
L.TileLayer.prototype.initialize.call(this, url, options);
},
createTile: function (coords, done) {
const url = this.getTileUrl(coords);
const img = document.createElement('img');
callAjax(
url,
function(response){
img.src = window.URL.createObjectURL(response);
done(null, img);
}
)
return img;
}
});
L.tileLayer.mapTilesAPI = function (url, options) {
return new L.TileLayer.MapTilesAPI(url, options);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment