首页 文章

如何将google Map 与路线转换为javascript中的图像

提问于
浏览
0

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

“未捕获的DOMException:无法在'HTMLCanvasElement'上执行'toDataURL':可能无法导出受污染的画布”

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

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

当我使用没有标记的谷歌 Map 意味着方向服务时,它不会来 . 当我在谷歌 Map 中使用方向服务时,它即将到来 .

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>

1 回答

  • 0

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

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

    为什么在存在折线时会有所不同,而在没有将折线添加到 Map 时,我无法解释 .

    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 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">
      </div>
    </div>
    
    <div id="show_img"></div>
    <button id="divclick">print</button>
    

相关问题