Anuradha
Anuradha

Reputation: 21

how to convert google map with route into image in javascript

I am trying to convert google map to the route into the png image. I am using canvas2image. I am succeeded with routes between markers in the map with javascript. But I'm trying to convert the image using html2canvas. But it says as:

"Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported"

Here is my code for exporting to the image:

$("#divclick").click(function () {
    html2canvas($("#totalimage"), {
        useCORS: true,
        onrendered: function (canvas) {
            alert(canvas.toDataURL("image/png"));
            $('#img_val').val(canvas.toDataURL("image/png"))
            $("#show_img").append(canvas);
        });
    }
});

It is not come when i am using google map without markers means direction services. It is coming when i am using direction services in google maps.

window.onload = function () {
        var mapOptions = {
            center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
            zoom: 10,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
        var infoWindow = new google.maps.InfoWindow();
        var lat_lng = new Array();
        var latlngbounds = new google.maps.LatLngBounds();
        for (i = 0; i < markers.length; i++) {
            var data = markers[i]
            var myLatlng = new google.maps.LatLng(data.lat, data.lng);
            lat_lng.push(myLatlng);
            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                title: data.title
            });
            latlngbounds.extend(marker.position);
            (function (marker, data) {
                google.maps.event.addListener(marker, "click", function (e) {
                    infoWindow.setContent(data.description);
                    infoWindow.open(map, marker);
                });
            })(marker, data);
        }
        map.setCenter(latlngbounds.getCenter());
        map.fitBounds(latlngbounds);
 
        //***********ROUTING****************//
 
        //Initialize the Path Array
        var path = new google.maps.MVCArray();
 
        //Initialize the Direction Service
        var service = new google.maps.DirectionsService();
 
        //Set the Path Stroke Color
        var poly = new google.maps.Polyline({ map: map, strokeColor: '#4986E7' });
 
        //Loop and Draw Path Route between the Points on MAP
        for (var i = 0; i < lat_lng.length; i++) {
            if ((i + 1) < lat_lng.length) {
                var src = lat_lng[i];
                var des = lat_lng[i + 1];
                path.push(src);
                poly.setPath(path);
                service.route({
                    origin: src,
                    destination: des,
                    travelMode: google.maps.DirectionsTravelMode.DRIVING
                }, function (result, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
                            path.push(result.routes[0].overview_path[i]);
                        }
                    }
                });
            }
        }
    }
    
    
    $(function() { 
 
      $("#divclick").click(function() { 
        html2canvas($("#totalimage"), {
        useCORS: true,
        onrendered: function (canvas) {
				
	        alert(canvas.toDataURL("image/png"));

          $('#img_val').val(canvas.toDataURL("image/png"))
	        $("#show_img").append(canvas);

          var img = new Image();

          img.onload = callback;
          img.setAttribute('crossOrigin', 'anonymous'); // works for me
				
          img.src = src;
				
          return img;
        }
      });
    });
});
var markers = [
            {
                "title": 'Alibaug',
                "lat": '18.641400',
                "lng": '72.872200',
                "description": 'Alibaug is a coastal town and a municipal council in Raigad District in the Konkan region of Maharashtra, India.'
            }
        ,
            {
                "title": 'Mumbai',
                "lat": '18.964700',
                "lng": '72.825800',
                "description": 'Mumbai formerly Bombay, is the capital city of the Indian state of Maharashtra.'
            }
        ,
            {
                "title": 'Pune',
                "lat": '18.523600',
                "lng": '73.847800',
                "description": 'Pune is the seventh largest metropolis in India, the second largest in the state of Maharashtra after Mumbai.'
            }
    ];
<script src="https://cdn.jsdelivr.net/npm/[email protected]/canvas2image.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <script src="https://maps.google.com/maps/api/js?&libraries=places&key=AIzaSyAHRgfjMojo9Q6LtvpmB40V39FZtYZTPJ0"></script>
<div id="totalimage">
<div id="dvMap" style="width: 100%; height: 500px">
</div>
</div>

<div id="show_img"></div>
 <button  id="divclick">print</button>

Upvotes: 1

Views: 4774

Answers (1)

geocodezip
geocodezip

Reputation: 161384

Looks like you need to set the marker's optimized property to false:

var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    optimized: false,
    title: data.title
});

Why that makes a difference when there is a polyline and not when the polyline isn't added to the map, I can't explain.

proof of concept fiddle

code snippet:

window.onload = function() {
  var mapOptions = {
    center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
    zoom: 10,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
  var infoWindow = new google.maps.InfoWindow();
  var lat_lng = new Array();
  var latlngbounds = new google.maps.LatLngBounds();
  for (i = 0; i < markers.length; i++) {
    var data = markers[i]
    var myLatlng = new google.maps.LatLng(data.lat, data.lng);
    lat_lng.push(myLatlng);
    var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: data.title,
      optimized: false
    });
    latlngbounds.extend(marker.position);
    (function(marker, data) {
      google.maps.event.addListener(marker, "click", function(e) {
        infoWindow.setContent(data.description);
        infoWindow.open(map, marker);
      });
    })(marker, data);
  }
  map.setCenter(latlngbounds.getCenter());
  map.fitBounds(latlngbounds);

  //***********ROUTING****************//

  //Initialize the Direction Service
  var service = new google.maps.DirectionsService();

  //Loop and Draw Path Route between the Points on MAP
  for (var i = 0; i < lat_lng.length; i++) {
    if ((i + 1) < lat_lng.length) {
      var src = lat_lng[i];
      var des = lat_lng[i + 1];
      // path.push(src);
      service.route({
        origin: src,
        destination: des,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
      }, function(result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          //Initialize the Path Array
          var path = new google.maps.MVCArray();
          //Set the Path Stroke Color
          var poly = new google.maps.Polyline({
            map: map,
            strokeColor: '#4986E7'
          });
          poly.setPath(path);
          for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
            path.push(result.routes[0].overview_path[i]);
          }
        }
      });
    }
  }
}

$(function() {
  $("#divclick").click(function() {
    html2canvas($("#totalimage"), {
      useCORS: true,
      onrendered: function(canvas) {
        console.log(canvas.toDataURL("image/png"));
        $('#img_val').val(canvas.toDataURL("image/png"))
        $("#show_img").append(canvas);
      }
    });
  });
});
var markers = [{
  "title": 'Alibaug',
  "lat": '18.641400',
  "lng": '72.872200',
  "description": 'Alibaug is a coastal town and a municipal council in Raigad District in the Konkan region of Maharashtra, India.'
}, {
  "title": 'Mumbai',
  "lat": '18.964700',
  "lng": '72.825800',
  "description": 'Mumbai formerly Bombay, is the capital city of the Indian state of Maharashtra.'
}, {
  "title": 'Pune',
  "lat": '18.523600',
  "lng": '73.847800',
  "description": 'Pune is the seventh largest metropolis in India, the second largest in the state of Maharashtra after Mumbai.'
}];
html,
body,
#dvMap {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px;
}

#totalimage {
  height: 80%;
  width: 100%;
}
<script>
<!-- prevent warning:
Google Maps JavaScript API has been loaded directly without a callback. This is not supported and can lead to race conditions and suboptimal performance. For supported loading patterns please see https://goo.gle/js-api-loading
-->
function dummy() {};
window.dummy = dummy;
</script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/canvas2image.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.google.com/maps/api/js?&libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=dummy"></script>
<div id="totalimage">
  <div id="dvMap">
  </div>
</div>

<div id="show_img"></div>
<button id="divclick">print</button>

Upvotes: 0

Related Questions