javascript - 如何在javascript中将带有路线的谷歌地图转换为图像

标签 javascript jquery google-maps html2canvas

我正在尝试将谷歌地图转换为 png 图像的路线。我正在使用 canvas2image。我成功地使用 javascript 在 map 中标记之间的路线。但我正在尝试使用 html2canvas 转换图像。但它说:

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

这是我导出到图像的代码:

$("#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);
        });
    }
});

当我使用没有标记的谷歌地图意味着方向服务时,它不会出现。当我在谷歌地图中使用方向服务时,它就来了。

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/canvas2image@1.0.5/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>

最佳答案

看起来您需要将标记的优化属性设置为 false:

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

为什么当有折线时会有所不同,而当折线未添加到 map 时则不会,我无法解释。

proof of concept fiddle

代码片段:

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/canvas2image@1.0.5/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>

关于javascript - 如何在javascript中将带有路线的谷歌地图转换为图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48149850/

相关文章:

iphone - 链接器找不到 _objc_msgSend 和许多其他符号

javascript - 在特定 block /div(包含可疑 HTML)中禁用 javascript?

javascript - 将数组值(vcard 参数)排序为变量

javascript - 如何使用 parseFloat(0.00) 获取 float

javascript - 为同名的多个类抓取浮点值

javascript - 来自异步加载的外部脚本的警告 : A call to document. write() 被忽略。这是如何固定的?

javascript - 如何交换下拉值?

javascript - jQuery 向动画队列添加函数

jquery - 如何让用户选择图片而不提交时自动上传任何图片?

android - Google Maps API key 是否缓存在 Android 上?