mapbox / mapbox.js-plugins

Hosted plugins for Leaflet & Mapbox.js
mapbox.com/mapbox.js/plugins/
BSD 2-Clause "Simplified" License
13 stars 16 forks source link

Area of Polygon #10

Closed brunosan closed 10 years ago

brunosan commented 10 years ago

Add a micro plugin to show the Area of a Polygon when drawing.

This would be useful for e.g. agriculture purposes. Draw a shape and know how many acres that is. (area of a field, lake, ...)

PS: This would need to be projection aware areas. (e.g. currently drawing a circle does not draw a circle on the "ground" -- it does not take into account the distortion due to projection--)

tmcw commented 10 years ago

See https://github.com/mapbox/leaflet-geodesy - would appreciate some tire-kicking of it

gundersen commented 10 years ago

@tmcw nice to flag this. @brunosan if you get this working I could see this being a hot little micro-site that lets us talk to agg folks.

brunosan commented 10 years ago

Thanks @tmcw .

Little time spent so far, but I´m going to jump to other things, so posting what I have:

function polygonArea(X, Y, numPoints) 
{ 
  area = 0;         // Accumulates area in the loop
  j = numPoints-1;  // The last vertex is the 'previous' one to the first

  for (i=0; i<numPoints; i++)
    { area = area +  (X[j]+X[i]) * (Y[j]-Y[i]); 
      j = i;  //j is previous vertex to i
    }
  return area/2;
}
map.on('draw:created', function (e) {
        var type = e.layerType,
            layer = e.layer;
            if (type === 'polygon') 
            {
                var area = L.GeometryUtil.geodesicArea(layer.getLatLngs())
                ...

But:

tmcw commented 10 years ago

The lower-level area implementation is in https://github.com/mapbox/geojson-area/blob/master/index.js#L1 - it is geodesic & should correctly handle polygons with holes

brunosan commented 10 years ago

Thanks @tmcw

Closing via https://www.mapbox.com/mapbox.js/example/v1.0.0/show-polygon-area/