當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Django Distance用法及代碼示例

本文介紹 django.contrib.gis.db.models.functions.Distance 的用法。

聲明

class Distance(expr1, expr2, spheroid=None, **extra)

Availability:MariaDB,MySQLPostGIS,甲骨文,SpatiaLite

接受兩個地理字段或表達式並返回它們之間的距離,作為 Distance 對象。在 MySQL 上,當坐標是大地時返回一個原始浮點值。

在支持大地坐標距離計算的後端上,根據幾何圖形的 SRID 值自動選擇適當的後端函數(例如 PostGIS 上的ST_DistanceSphere)。

當使用大地(角)坐標計算距離時,與默認 WGS84 (4326) SRID 的情況一樣,您可以設置 spheroid 關鍵字參數來決定計算是否應基於簡單的球體(不太準確,較少resource-intensive)或在球體上(更準確,更多 resource-intensive)。

在以下示例中,計算了從霍巴特市到 AustraliaCity 查詢集中其他所有 PointField 的距離:

>>> from django.contrib.gis.db.models.functions import Distance
>>> pnt = AustraliaCity.objects.get(name='Hobart').point
>>> for city in AustraliaCity.objects.annotate(distance=Distance('point', pnt)):
...     print(city.name, city.distance)
Wollongong 990071.220408 m
Shellharbour 972804.613941 m
Thirroul 1002334.36351 m
...

注意

因為distance 屬性是一個 Distance 對象,您可以輕鬆地以您選擇的單位表示該值。例如,city.distance.mi 是以英裏為單位的距離值,city.distance.km 是以公裏為單位的距離值。有關使用詳細信息和支持的單位列表,請參閱測量對象。

相關用法


注:本文由純淨天空篩選整理自djangoproject.com大神的英文原創作品 django.contrib.gis.db.models.functions.Distance。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。