GeoDjango:确定多边形的面积

时间:2013-11-10 17:47:06

标签: django gis polygon area geodjango

在我的模型中,我有一个通过

定义的多边形字段
polygon = models.PolygonField(srid=4326, geography=True, null=True, blank=True)

当我想确定多边形的区域时,我调用

area_square_degrees = object.polygon.area

但是如何使用GeoDjango将square degrees中的结果转换为m2? This answer不起作用,因为area没有方法sq_m。有内置转换吗?

3 个答案:

答案 0 :(得分:0)

我需要一个应用程序来获取全球各地的poligons区域,如果我使用了无效的国家/地区投影,我收到错误OGRException: OGR failure

我结束了使用OpenLayers implementation 使用4326投影(是默认投影)以避免涉及每个国家/地区的特定投影。 这是我的代码:

import math

def getCoordsM2(coordinates):
    d2r = 0.017453292519943295  # Degrees to radiant
    area = 0.0
    for coord in range(0, len(coordinates)):
        point_1 = coordinates[coord]
        point_2 = coordinates[(coord + 1) % len(coordinates)]
        area += ((point_2[0] - point_1[0]) * d2r) *\
            (2 + math.sin(point_1[1] * d2r) + math.sin(point_2[1] * d2r))
    area = area * 6378137.0 * 6378137.0 / 2.0
    return math.fabs(area)

def getGeometryM2(geometry):
    area = 0.0
    if geometry.num_coords > 2:
        # Outer ring
        area += getCoordsM2(geometry.coords[0])
        # Inner rings
        for counter, coordinates in enumerate(geometry.coords):
            if counter > 0:
                area -= getCoordsM2(coordinates)
    return area

只需将几何图形传递给getGeometryM2函数即可完成! 我在我的GeoDjango模型中使用此函数作为属性。 希望它有所帮助!

答案 1 :(得分:0)

我为此付出了很多努力,因为我无法找到一个干净的解决方案。诀窍是你必须使用postgis功能(因此它只能使用postgis ..):

from django.contrib.gis.db.models.functions import Area
loc_obj = Location.objects.annotate(area_=Area("poly")).get(pk=??)  
# put the primary key of the object

print(loc_obj.area_)  # distance object, result should be in meters, but you can change to the unit you want, e.g  .mi for miles etc..

models.py:

class Location(models.Model):
    poly = gis_models.PolygonField(srid=4326, geography=True)

如果您必须处理地理坐标而不是投影,我认为这是最好的方法。它确实处理地球的曲线计算,即使距离/面积很大,结果也很精确

答案 2 :(得分:-3)

如果你说的是地球表面区域,1平方度有12,365.1613平方公里。所以多个你的平方度并乘以10 ^ 6转换为米。

相关问题