leaflet地圖全圖以及框選截圖導出功能(附源碼下載)

前言

leaflet 入門開發系列環境知識點了解:

內容概覽

leaflet地圖截圖導出功能
源代碼demo下載

效果圖如下:

本篇主要參考截圖插件domtoimage:https://github.com/tsayen/dom-to-image
地圖全圖導出直接用上面的domtoimage插件,然后矩形框選截圖導出也是在domtoimage插件基礎上自己計算矩形范圍來實現的

  • 部分代碼,完整的見源碼demo下載
<script> 
 var geojsonLayer = null; 
 var map = L.map('map'); 
  L.tileLayer('http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}',{crossOrigin:true}).addTo(map); 
 
  map.setView(L.latLng(22.95186415, 113.90271877), 14);  //設置縮放級別及中心點 
 
  map.pm.addControls({ 
 position: 'topleft', 
 drawCircle: false, 
 drawMarker:false, 
 drawCircleMarker:false, 
 drawPolyline:false, 
 drawRectangle:false, 
 drawPolygon:false, 
 cutPolygon:false, 
 removalMode:false, 
 editMode:false, 
 dragMode:false 
  }); 
 //參考截圖插件:https://github.com/tsayen/dom-to-image 
 var node = document.getElementById('map'); 
  $("#mapexport_btn").click(function(){ 
      domtoimage.toJpeg(node, { quality: 1.0 }) 
        .then(function (dataUrl) { 
 var link = document.createElement('a'); 
            link.download = '全圖導出.jpeg'; 
            link.href = dataUrl; 
            link.click(); 
        }); 
  }); 
  $("#rctanglexport_btn").click(function(){ 
 //繪制矩形 
      map.pm.enableDraw("Rectangle", { 
 finishOn: "dblclick", 
 allowSelfIntersection: false, 
 tooltips: false 
      }); 
  }); 
  map.on('pm:create', e => { 
 //console.log(e); 
    geojsonLayer = e.layer; 
    geojsonLayer.addTo(map); 
 
 var northEast =  e.layer.getBounds()._northEast; 
 var southWest =  e.layer.getBounds()._southWest; 
 //框選矩形的中心點 
 var centerPoint = L.latLng( 
          (northEast.lat + southWest.lat) / 2.0, 
          (northEast.lng + southWest.lng) / 2.0 
    ); 
 //地理坐標轉換屏幕坐標 
 var northEastPoint = map.latLngToContainerPoint(northEast); 
 var southWestPoint = map.latLngToContainerPoint(southWest); 
 ……
 ……
 
 if(geojsonLayer){ 
         map.removeLayer(geojsonLayer); 
         geojsonLayer = null; 
    } 
    domtoimage 
          .toPng(node) 
          .then(function(dataUrl) { 
 if (dataUrl.length <= 6) { 
 console.log("屏幕截圖結果為空,建議放大地圖,重新截圖操作試試看"); 
 return; 
            } 
 //過渡img圖片,為了截取img指定位置的截圖需要 
 var img = new Image(); 
            img.src = dataUrl; 
            img.onload = function() { 
               ……
               ……
            }; 
          }) 
          .catch(function(error) { 
 console.error("oops, something went wrong!", error); 
          }); 
  }); 
</script> 

完整demo源碼見小專欄文章尾部小專欄

文章尾部提供源代碼下載,對本專欄感興趣的話,可以關注一波

posted @ 2020-03-29 09:43  GIS之家  閱讀(...)  評論(...編輯  收藏
最新chease0ldman老人