Created
October 26, 2021 08:11
-
-
Save stephanbogner/e508438a2c457793a5b8760f51962543 to your computer and use it in GitHub Desktop.
Download map canvas as png from Mapbox GL JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset='utf-8' /> | |
<title>Display a map</title> | |
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' /> | |
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.44.1/mapbox-gl.js'></script> | |
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.44.1/mapbox-gl.css' rel='stylesheet' /> | |
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> | |
<style> | |
#map { | |
margin: auto; | |
width: 400px; | |
height: 400px; | |
} | |
</style> | |
</head> | |
<body> | |
<div id='map'></div> | |
<a id="downloadLink" href="" download="map.png">Download ↓</a> | |
<div id="image"></div> | |
<script> | |
mapboxgl.accessToken = '{your-access-token-here}'; | |
/* The important part is line 33: preserveDrawingBuffer: true */ | |
var map = new mapboxgl.Map({ | |
container: 'map', | |
style: 'mapbox://styles/mapbox/streets-v9', | |
center: [-74.50, 40], | |
zoom: 9, | |
preserveDrawingBuffer: true | |
}); | |
$('#downloadLink').click(function() { | |
var img = map.getCanvas().toDataURL('image/png') | |
this.href = img | |
}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment