如何使用leaflet.draw从多边形中获取区域字符串

16

我正在尝试获取多边形的面积测量值,以便在地图旁边的表格中列出它们,与多边形的名称相邻。这是我的尝试但没有成功:

$("#polygon").on("click", function (){
    createPolygon = new L.Draw.Polygon(map, drawControl.options.polygon);
    createPolygon.enable();
}

var polygon = new L.featureGroup();

map.on('draw:created', function (e) {
    var type = e.layerType,
        layer = e.layer;
    if (type === 'polygon') {
      polygons.addLayer(layer);
    }
    var seeArea = createPolygon._getMeasurementString();
   console.log(seeArea);  //Returns null
}
任何对此的帮助将不胜感激!

请问您能否添加一个 Fiddle? - Manuel
4个回答

24
您可以访问 Leaflet 提供的几何实用库。
var area = L.GeometryUtil.geodesicArea(layer.getLatLngs());

在您的例子中,您试图访问控件本身,也就是变量createPolygon所分配的内容。相反,您想要获取绘制的图层的面积。

map.on('draw:created', function (e) {
  var type = e.layerType,
      layer = e.layer;
  if (type === 'polygon') {
    polygons.addLayer(layer);
    var seeArea = L.GeometryUtil.geodesicArea(layer.getLatLngs());
    console.log(seeArea);
  }
}

一旦确认您已经获得了这个区域,您可以将其分配给变量,这些变量将填充地图旁边的表格。

注意:默认情况下,面积将以平方米为单位。


9
请注意,这里提到的几何图形实用库是指:Leaflet.draw - Orienteerix
1
这对我不起作用:https://stackoverflow.com/q/60827549/274677 - Marcus Junius Brutus
2
我一直得到面积等于0的结果。 - Deepika Rao
3
您需要访问getLatLngs结果的第一个位置:let seeArea = L.GeometryUtil.geodesicArea(layer.getLatLngs()[0]); - Juan Antonio
由于layer.getLatLngs()是一个嵌套数组,所以我们需要获取第一位置layer.getLatLngs()[0] - aijogja

4

L.GeometryUtil.geodesicArea(layer.getLatLngs())[0] 可以获得面积。

但我最终使用了 leaflet-geoman-free 进行绘制,并使用 turf.js 获得面积。

map.pm.enableDraw('Polygon', {
   snappable: true,
   snapDistance: 20,
});

map.on('pm:create', e => {
   const layer = e.layer
   alert(turf.area(layer.toGeoJSON()))
});

3

添加更正:

var seeArea = L.GeometryUtil.geodesicArea(layer.getLatLngs()[0]);
console.log(seeArea);

3

我发现以上答案都无法计算非连续多边形的面积。下面是一个示例多边形,其中上述函数返回了0的面积:

Non-contiguous Polygon

对于任何需要这样做的人,以下是适用于我(使用Leaflet.draw的L.GeometryUtil函数)的代码:

var poly = // Your polygon layer here; may or may not be contiguous
var area = 0;
for (island of poly.getLatLngs()) {
    // If the polygon is non-contiguous, access the island
    if (island.length < 2) {
        island = island[0]
    }
    // Sum the area within each "island"
    area += L.GeometryUtil.geodesicArea(island);
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接