I am just starting out with javascript and I am trying to create an interactive web map....
I want to be able to position the map then press a button that will take a screenshot and save it to the computer.
Here is the code for my map.....
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Display a map on a webpage</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
<link href="https://api.mapbox.com/mapbox-gl-js/v2.9.1/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v2.9.1/mapbox-gl.js"></script>
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoiY2hhcmxpZS1lbnJpZ2h0IiwiYSI6ImNsNG13MnJtMjE2emEzb254ZmlodjB4MjYifQ.eOB792QFvjLfcI8eN_1aUw';
const map = new mapboxgl.Map({
container: 'map', // container ID
style: 'mapbox://styles/charlie-enright/cl5b8bjil002y14o5u8xrssah', // style URL
center: [-4.369240916438415, 51.925803756014965], // starting position [lng, lat]
zoom: 8, // starting zoom
projection: 'globe' // display the map as a 3D globe
});
map.on('style.load', () => {
map.setFog({}); // Set the default atmosphere style
});
</script>
</body>
</html>
I have tried using html2canvas (https://codepen.io/samsammurphy/pen/VXdOPv) but the button seems to end up in a layer behind my map and I can not take a screenshot of the displayed map.
Any ideas how I could create a button that allows for a screenshot to be taken which saves to the computer will be greatly appreciated.
Thanks,
CodePudding user response:
Here's an example of using map.getCanvas().toDataURL()
and then injecting an img
tag into the DOM. (This is not my example, I found it on this codepen by Sam Murphy https://codepen.io/samsammurphy/pen/VXdOPv)
$('button').click(function() {
var img = map.getCanvas().toDataURL();
var width = $('#screenshotPlaceholder').width()
var height = $('#screenshotPlaceholder').height()
var imgHTML = `<img src="${img}", width=${width}, height = ${height}/>`
$('#screenshotPlaceholder').empty();
$('#screenshotPlaceholder').append(imgHTML);
});
});
The codepen I found this on was not working due to an expired access token, so here's a fork that works if you want to try it out.
https://codepen.io/chriswhong/pen/YzapomG
CodePudding user response:
Here's the code I use to take map screenshots using html2canvas
html2canvas(document.getElementById("map"), {useCORS:true}).then(canvas => {
var pseudolink = document.createElement('a');
pseudolink.download = 'myMapScreenshot.png';
pseudolink.href = canvas.toDataURL()
pseudolink.click();
})