Google canvas capture
by felixp
HTML
<!DOCTYPE html>
<html>
<head>
<title>Google map</title>
<script async src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&v=weekly&map_ids=fae05836df2dc8bb&callback=initMap"></script>
</head>
<body>
<div id="map"></div>
<button id="capture">Capture</button>
</body>
</html>
CSS
/* Always set the map height explicitly to define the size of the div element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#capture {
position: absolute;
bottom: 50px;
left: 10px;
z-index: 2;
}
JavaScript
let webglOverlayView = null;
let captureRequested = false
document.getElementById('capture').addEventListener('click', function() {
captureRequested = true;
webglOverlayView.requestRedraw(true);
});
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
center: {
lat: 40,
lng: -120
},
gestureHandling: 'greedy',
mapId: 'fae05836df2dc8bb',
zoom: 3
});
window.mm = map;
webglOverlayView = new google.maps.WebGLOverlayView();
// Add the overlay to the map.
webglOverlayView.setMap(map);
// Need to implement all these methods otherwise get errors
webglOverlayView.onAdd = () => {};
webglOverlayView.onContextRestored = ({
gl
}) => {};
webglOverlayView.onContextLost = () => {};
webglOverlayView.onRemove = () => {};
webglOverlayView.onStateUpdate = ({
gl
}) => {
console.log('update'); // <-- Never gets called it seems
};
webglOverlayView.onDraw = ({
gl
}) => {
if (captureRequested) {
captureRequested = false;
const { canvas} = gl;
let a = document.createElement('a');
// toDataURL defaults to png then convert for file download.
a.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
a.download = 'screenshot.png';
a.click();
}
};
webglOverlayView.setMap(map);
}
// initMap is invoked via callback defined in script tag