前言
leaflet 入门开发系列环境知识点了解:
- leaflet api文档介绍,详细介绍 leaflet 每个类的函数以及属性等等
- leaflet 在线例子
- 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源码见小专栏文章尾部:小专栏
文章尾部提供源代码下载,对本专栏感兴趣的话,可以关注一波
原文地址:https://www.cnblogs.com/giserhome/p/12590932.html
时间: 2024-10-10 09:50:32