googlemaps-v3-print
by Glenn Dwiyatcita
HTML
<script src="//maps.googleapis.com/maps/api/js?key=AIzaSyDkT5IxC3XOeHVkM7PBFnOd6Etp02VERRc"></script>
<script src="//rawgit.com/mahnunchik/markerclustererplus/master/dist/markerclusterer.min.js"></script>
<script src="https://unpkg.com/lodash@latest/lodash.min.js"></script>
<div class="map-container"></div>
<button class="map-print">print</button>
CSS
body {
margin: 8px;
}
.map-container {
width: 640px;
height: 480px;
margin: .4rem;;
}
JavaScript
/**
* My very own *not* quite hackish approach to workaround Google Maps printing,
* crafted with <3.
* @see http://stackoverflow.com/q/13050215/2013891
*/
$(function () {
// Java
const center = new google.maps.LatLng(-7.4917, 110.0044);
// Jakarta, Bogor, Bekasi, Tangerang, Surabaya
const locations = [
{ lat: -6.1745, lng: 106.8227 },
{ lat: -6.6000, lng: 106.8000 },
{ lat: -6.2333, lng: 107.0000 },
{ lat: -6.1783, lng: 106.6319 },
{ lat: -7.2653, lng: 112.7425 }
];
const mapContainer = $('.map-container');
const map = new google.maps.Map(mapContainer[0], {
center,
zoom: 5
});
const markers = _(locations)
.map(({ lat, lng }) => new google.maps.Marker({
position: new google.maps.LatLng(lat, lng)
}))
.forEach(_.curry(_, _.invoke('setMap', map)));
new MarkerClusterer(map, markers);
const [
directionsDisplay,
directionsService
] = [
new google.maps.DirectionsRenderer(),
new google.maps.DirectionsService()
];
directionsDisplay.setMap(map);
(function displayRoute() {
directionsService.route({
origin: 'Jakarta',
destination: 'Bandung',
travelMode: google.maps.TravelMode.DRIVING
}, (response, status) => {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
console.log(`Directions request failed due to ${status}`);
}
});
}());
$('.map-print').on('click',
// printAnyMaps ::
function printAnyMaps() {
const $body = $('body');
const $mapContainer = $('.map-container');
const $mapContainerParent = $mapContainer.parent();
const $printContainer = $('<div style="position:relative;">');
$printContainer
.height($mapContainer.height())
.append($mapContainer)
.prependTo($body);
const $content = $body
.children()
.not($printContainer)
.not('script')
.detach();
...