Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

javascript - How to get the area string from a polygon using leaflet.draw

I am trying to get the area measurements of polygons so I can list them in a table to the side of the map, next to the name of the polygon. This is what I have tried with no success:

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

Any help on this would be appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can access the geometry utility library provided with Leaflet.

var area = L.GeometryUtil.geodesicArea(layer.getLatLngs());

In your example, you are trying to access a control itself, which is what the variable createPolygon is assigned to. Instead, you want to take the area of the layer that got drawn.

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);
  }
}

Once you verify you are getting the area, you can just assign it to the variables that populate the table next to the map.

Note: area will be in squareMeters by default


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...