基于Leaflet.draw的自定义绘制实战

        之前的文章(基于Leaflet.draw的gis图形标绘实战)提过如何基于leaflet.draw插件进行基本图形的标绘。在实际项目中,你一定还会遇到以下的需求:在不需要Leaflet.draw按钮触发的事件中绘制一个矩形框,用来生成一个地理空间bbox范围,或者需要自定义绘制一条线,并获取绘制对象的Geojson。

        一、如何自定义按钮,并绑定绘制的方法

        其实,在不使用LeafLet.draw的前提下,你依然可以通过leaflet的api进行图形绘制。只是我们使用leaflet.draw可以更加流畅的使用绘制功能。前面的内容提过,以下代码为基本标绘的触发绑定代码。

map.addControl(new L.Control.Draw({
                edit: {
                featureGroup: drawnItems,
                poly : {
                    allowIntersection : false
                }
            },
            draw: {
                polygon : {
                    allowIntersection: false,
                    showArea:true
                }
            }
        }));

        而在一些场景中,我们只想通过一个按钮就激发绘制功能。这该如何实现呢?好在leafLet.draw本身提供了扩展。

        二、功能按钮定义

<div style="position: absolute;top: 15px;right: 15px;z-index: 401;">
	<button type="button" onclick="drawRectangle();">绘制矩形</button>
	<button type="button" onclick="getBbox();">获取bbox</button>
	<button type="button" onclick="getGeojson();">获取Geojson</button>
	<br/>
	<button type="button" onclick="drawLine();">绘制线</button>
</div>

        首先定义了四个按钮,关键代码如上所示:

        三、手动开启绘制

function drawRectangle(){
			console.log("开始绘制矩形...");
			diyDrawLayers.clearLayers();
			new L.Draw.Rectangle4Diy(map).enable();
		}

        通过enable()方法直接触发矩形绘制,我们来看下实际效果:

图片

        四、获取FeatureGroup的bbox

function getBbox(){
			console.log("获取bbox...");
			var bounds = diyDrawLayers.getBounds();
			console.log("bbox==>" + bounds);
			console.log("_northEast==>" + bounds._northEast);
			console.log("_southWest==>" + bounds._southWest);
		}

图片

        五、获取FeatureGroup的Geojson

function getGeojson(){
			console.log("获取getGeojson...");
			console.log(diyDrawLayers.toGeoJSON());
		}

图片

        六、FeatureGroup图层定义

var diyDrawLayers = L.featureGroup().addTo(map);

        通过以上几个步骤,大致完成了在不依赖leaflet.draw的前提下,直接使用按钮进行矩形绘制,同时获取绘制的矩形bbox的值(可以用来做空间查询),并获取绘制矩形的Geojson。如果文章对你有帮助,欢迎给个赞,有疑问,欢迎留言指正。

猜你喜欢

转载自blog.csdn.net/yelangkingwuzuhu/article/details/121875770