API GEOS

Contexte

Qu’est-ce que GEOS ?

GEOS stands for Geometry Engine - Open Source, and is a C++ library, ported from the Java Topology Suite. GEOS implements the OpenGIS Simple Features for SQL spatial predicate functions and spatial operators. GEOS, now an OSGeo project, was initially developed and maintained by Refractions Research of Victoria, Canada.

Fonctionnalités

GeoDjango implémente une adaptation Python de haut niveau de la bibliothèque GEOS. Ses fonctionnalités comprennent notamment :

  • Une interface sous licence BSD des routines géométriques GEOS, implémentées purement en Python à l’aide de ctypes.

  • Loosely-coupled to GeoDjango. For example, GEOSGeometry objects may be used outside of a Django project/application. In other words, no need to have DJANGO_SETTINGS_MODULE set or use a database, etc.

  • Mutabilité : les objets GEOSGeometry peuvent être modifiés.

  • Testé sur toutes les plates-formes.

Tutoriel

Cette section contient une brève introduction à l’utilisation des objets GEOSGeometry.

Création d’un objet géométrique

GEOSGeometry objects may be created in a few ways. The first is to simply instantiate the object on some spatial input – the following are examples of creating the same geometry from WKT, HEX, WKB, and GeoJSON:

>>> from django.contrib.gis.geos import GEOSGeometry
>>> pnt = GEOSGeometry("POINT(5 23)")  # WKT
>>> pnt = GEOSGeometry("010100000000000000000014400000000000003740")  # HEX
>>> pnt = GEOSGeometry(
...     memoryview(
...         b"\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x14@\x00\x00\x00\x00\x00\x007@"
...     )
... )  # WKB
>>> pnt = GEOSGeometry(
...     '{ "type": "Point", "coordinates": [ 5.000000, 23.000000 ] }'
... )  # GeoJSON

Another option is to use the constructor for the specific geometry type that you wish to create. For example, a Point object may be created by passing in the X and Y coordinates into its constructor:

>>> from django.contrib.gis.geos import Point
>>> pnt = Point(5, 23)

Tous ces constructeurs acceptent le paramètre nommé srid. Par exemple :

>>> from django.contrib.gis.geos import GEOSGeometry, LineString, Point
>>> print(GEOSGeometry("POINT (0 0)", srid=4326))
SRID=4326;POINT (0 0)
>>> print(LineString((0, 0), (1, 1), srid=4326))
SRID=4326;LINESTRING (0 0, 1 1)
>>> print(Point(0, 0, srid=32140))
SRID=32140;POINT (0 0)

Pour terminer, il existe la méthode de fabrication fromfile() qui renvoie un objet GEOSGeometry à partir d’un fichier :

>>> from django.contrib.gis.geos import fromfile
>>> pnt = fromfile("/path/to/pnt.wkt")
>>> pnt = fromfile(open("/path/to/pnt.wkt"))

Les objets géométriques sont « pythonesques »

Les objets GEOSGeometry sont « pythonesques », ce qui signifie qu’il est possible d’accéder, de modifier ou de passer en boucle leurs composants à l’aide des conventions Python standards. Par exemple, voici comment parcourir les coordonnées d’un Point en boucle :

>>> pnt = Point(5, 23)
>>> [coord for coord in pnt]
[5.0, 23.0]

Avec n’importe quel objet géométrique, la propriété GEOSGeometry.coords peut être utilisée pour obtenir les coordonnées géométriques sous forme de tuple Python :

>>> pnt.coords
(5.0, 23.0)

You can get/set geometry components using standard Python indexing techniques. However, what is returned depends on the geometry type of the object. For example, indexing on a LineString returns a coordinate tuple:

>>> from django.contrib.gis.geos import LineString
>>> line = LineString((0, 0), (0, 50), (50, 50), (50, 0), (0, 0))
>>> line[0]
(0.0, 0.0)
>>> line[-2]
(50.0, 0.0)

Alors que l’application d’un indice sur un Polygon renvoie un anneau (un objet LinearRing) correspondant à l’indice :

>>> from django.contrib.gis.geos import Polygon
>>> poly = Polygon(((0.0, 0.0), (0.0, 50.0), (50.0, 50.0), (50.0, 0.0), (0.0, 0.0)))
>>> poly[0]
<LinearRing object at 0x1044395b0>
>>> poly[0][-2]  # second-to-last coordinate of external ring
(50.0, 0.0)

De plus, les coordonnées et les composants d’un objet géométrique peuvent être complétés ou modifiés de manière similaire à une liste Python :

>>> line[0] = (1.0, 1.0)
>>> line.pop()
(0.0, 0.0)
>>> line.append((1.0, 1.0))
>>> line.coords
((1.0, 1.0), (0.0, 50.0), (50.0, 50.0), (50.0, 0.0), (1.0, 1.0))

Les objets géométriques prennent en charge les opérateurs d’ensembles (set) :

>>> from django.contrib.gis.geos import LineString
>>> ls1 = LineString((0, 0), (2, 2))
>>> ls2 = LineString((1, 1), (3, 3))
>>> print(ls1 | ls2)  # equivalent to `ls1.union(ls2)`
MULTILINESTRING ((0 0, 1 1), (1 1, 2 2), (2 2, 3 3))
>>> print(ls1 & ls2)  # equivalent to `ls1.intersection(ls2)`
LINESTRING (1 1, 2 2)
>>> print(ls1 - ls2)  # equivalent to `ls1.difference(ls2)`
LINESTRING(0 0, 1 1)
>>> print(ls1 ^ ls2)  # equivalent to `ls1.sym_difference(ls2)`
MULTILINESTRING ((0 0, 1 1), (2 2, 3 3))

L’opérateur d’égalité ne vérifie pas l’égalité spatiale

L’opérateur d’égalité de GEOSGeometry utilise equals_exact(), et non pas equals(), c’est-à-dire que l’égalité dépend de coordonnées identiques, dans la même position et avec les mêmes SRID :

>>> from django.contrib.gis.geos import LineString
>>> ls1 = LineString((0, 0), (1, 1))
>>> ls2 = LineString((1, 1), (0, 0))
>>> ls3 = LineString((1, 1), (0, 0), srid=4326)
>>> ls1.equals(ls2)
True
>>> ls1 == ls2
False
>>> ls3 == ls2  # different SRIDs
False

Objets géométriques

GEOSGeometry

class GEOSGeometry(geo_input, srid=None)[source]
Paramètres:
  • geo_input – Valeur d’entrée géométrique (chaîne ou memoryview)

  • srid (int) – identifiant de référence spatiale

This is the base class for all GEOS geometry objects. It initializes on the given geo_input argument, and then assumes the proper geometry subclass (e.g., GEOSGeometry('POINT(1 1)') will create a Point object).

Le paramètre srid, s’il est présent, est défini comme le SRID de l’objet géométrique créé si geo_input ne possède pas de SRID. Si les valeurs de SRID entre les paramètres geo_input et srid diffèrent, une erreur ValueError est produite :

>>> from django.contrib.gis.geos import GEOSGeometry
>>> GEOSGeometry("POINT EMPTY", srid=4326).ewkt
'SRID=4326;POINT EMPTY'
>>> GEOSGeometry("SRID=4326;POINT EMPTY", srid=4326).ewkt
'SRID=4326;POINT EMPTY'
>>> GEOSGeometry("SRID=1;POINT EMPTY", srid=4326)
Traceback (most recent call last):
...
ValueError: Input geometry already has SRID: 1.

Les formats de valeurs d’entrée suivants, ainsi que leur type Python correspondant, sont acceptés :

Format

Type en entrée

WKT / EWKT

str

HEX / HEXEWKB

str

WKB / EWKB

memoryview

GeoJSON

str

Pour le format GeoJSON, le SRID est défini sur la base du membre crs. SI crs n’est pas fourni, le SRID par défaut est 4326.

classmethod GEOSGeometry.from_gml(gml_string)

Construit un objet GEOSGeometry à partir de la chaîne GML donnée.

Propriétés

GEOSGeometry.coords

Renvoie les coordonnées de l’objet géométrique sous forme de tuple.

GEOSGeometry.dims

Renvoie la dimension de l’objet géométrique :

GEOSGeometry.empty

Renvoie une valeur booléenne indiquant si l’ensemble des points de l’objet géométrique est vide.

GEOSGeometry.geom_type

Returns a string corresponding to the type of geometry. For example:

>>> pnt = GEOSGeometry("POINT(5 23)")
>>> pnt.geom_type
'Point'
GEOSGeometry.geom_typeid

Returns the GEOS geometry type identification number. The following table shows the value for each geometry type:

Objet géométrique

ID

Point

0

LineString

1

LinearRing

2

Polygon

3

MultiPoint

4

MultiLineString

5

MultiPolygon

6

GeometryCollection

7

GEOSGeometry.num_coords

Renvoie le nombre de coordonnées de l’objet géométrique.

GEOSGeometry.num_geom

Returns the number of geometries in this geometry. In other words, will return 1 on anything but geometry collections.

GEOSGeometry.hasz

Returns a boolean indicating whether the geometry has the Z dimension.

GEOSGeometry.hasm
New in Django 6.0.

Returns a boolean indicating whether the geometry has the M dimension. Requires GEOS 3.12.

GEOSGeometry.ring

Renvoie une valeur booléenne indiquant si l’objet géométrique est un LinearRing.

GEOSGeometry.simple

Returns a boolean indicating whether the geometry is “simple”. A geometry is simple if and only if it does not intersect itself (except at boundary points). For example, a LineString object is not simple if it intersects itself. Thus, LinearRing and Polygon objects are always simple because they cannot intersect themselves, by definition.

GEOSGeometry.valid

Renvoie une valeur booléenne indiquant si l’objet géométrique est valide.

GEOSGeometry.valid_reason

Renvoie une chaîne décrivant la raison pour laquelle un objet géométrique n’est pas valable.

GEOSGeometry.srid

Property that may be used to retrieve or set the SRID associated with the geometry. For example:

>>> pnt = Point(5, 23)
>>> print(pnt.srid)
None
>>> pnt.srid = 4326
>>> pnt.srid
4326

Propriétés en sortie

The properties in this section export the GEOSGeometry object into a different. This output may be in the form of a string, buffer, or even another object.

GEOSGeometry.ewkt

Returns the « extended » Well-Known Text of the geometry. This representation is specific to PostGIS and is a superset of the OGC WKT standard. [1] Essentially the SRID is prepended to the WKT representation, for example SRID=4326;POINT(5 23).

Note

Le résultat de cette propriété n’inclut pas les informations 3dm, 3dz ou 4d que PostGIS prend en charge dans ses représentations EWKT.

GEOSGeometry.hex

Returns the WKB of this Geometry in hexadecimal form. Please note that the SRID value is not included in this representation because it is not a part of the OGC specification (use the GEOSGeometry.hexewkb property instead).

GEOSGeometry.hexewkb

Returns the EWKB of this Geometry in hexadecimal form. This is an extension of the WKB specification that includes the SRID value that are a part of this geometry.

GEOSGeometry.json

Renvoie la représentation GeoJSON de l’objet géométrique. Notez que le résultat ne constitue pas une structure GeoJSON complète, mais seulement le contenu de la clé geometry d’une structure GeoJSON. Voir aussi Sérialisation GeoJSON.

GEOSGeometry.geojson

Alias de GEOSGeometry.json.

GEOSGeometry.kml

Returns a KML (Keyhole Markup Language) representation of the geometry. This should only be used for geometries with an SRID of 4326 (WGS84), but this restriction is not enforced.

GEOSGeometry.ogr

Renvoie un objet OGRGeometry équivalent à l’objet géométrique GEOS.

GEOSGeometry.wkb

Returns the WKB (Well-Known Binary) representation of this Geometry as a Python buffer. SRID value is not included, use the GEOSGeometry.ewkb property instead.

GEOSGeometry.ewkb

Renvoie la représentation EWKB de cet objet géométrique sous forme de tampon Python (buffer). Il s’agit d’une extension de la spécification WKB qui inclut toute valeur SRID faisant partie de cet objet.

GEOSGeometry.wkt

Renvoie la représentation WKT (Well-Known Text) de cet objet géométrique (un standard OGC).

Méthodes de prédicats spatiaux

Toutes les méthodes de prédicats spatiaux ci-après acceptent en paramètre une autre instance GEOSGeometry (other) et renvoient une valeur booléenne.

GEOSGeometry.contains(other)

Renvoie True si other.within(this) renvoie True.

GEOSGeometry.covers(other)

Renvoie True si cet objet géométrique recouvre l’objet géométrique donné.

Le prédicat covers possède les définitions équivalentes suivantes :

  • Chaque point de l’autre objet géométrique est un point de cet objet géométrique.

  • La matrice d’intersection DE-9IM des deux objets géométriques est T*****FF*, *T****FF*, ***T**FF* ou ****T*FF*.

Si l’un des objets géométriques est vide, renvoie False.

Ce prédicat est semblable à GEOSGeometry.contains(), mais est plus inclusif (c’est-à-dire qu’il renvoie True dans plus de cas). En particulier, au contraire de contains(), il ne distingue pas entre les points à la limite et ceux à l’intérieur de l’objet géométrique. Dans la plupart des situations, covers() devrait être préféré à contains(). Comme bénéfice supplémentaire, covers() est plus sujet à l’optimisation et devrait donc être bien plus performant que contains().

GEOSGeometry.crosses(other)

Renvoie True si la matrice d’intersection DE-9IM des deux objets géométriques est T*T****** (pour un point et une courbe, un point et une aire ou une ligne et une aire), ou 0******** (pour deux courbes).

GEOSGeometry.disjoint(other)

Renvoie True si la matrice d’intersection DE-9IM des deux objets géométriques est FF*FF****.

GEOSGeometry.equals(other)

Renvoie True si la matrice d’intersection DE-9IM des deux objets géométriques est T*F**FFF*.

GEOSGeometry.equals_exact(other, tolerance=0)

Returns true if the two geometries are exactly equal, up to a specified tolerance. The tolerance value should be a floating point number representing the error tolerance in the comparison, e.g., poly1.equals_exact(poly2, 0.001) will compare equality to within one thousandth of a unit.

GEOSGeometry.equals_identical(other)

Renvoie True si les deux objets géométriques sont équivalents point par point en vérifiant que leur structure, leur ordre de tri et les valeurs de toutes les arêtes sont identiques dans toutes les dimensions. Les valeurs NaN sont considérées comme égales à d’autres valeurs NaN. Exige GEOS 3.12.

GEOSGeometry.intersects(other)

Renvoie True si GEOSGeometry.disjoint() vaut False.

GEOSGeometry.overlaps(other)

Renvoie True si la matrice d’intersection DE-9IM des deux objets géométriques est T*T***T** (pour deux points ou deux surfaces), ou 1*T***T** (pour deux courbes).

GEOSGeometry.relate_pattern(other, pattern)

Renvoie True si la matrice d’intersection DE-9IM des deux objets géométriques correspond au motif pattern donné, une chaîne de neuf caractères dans l’alphabet {T, F, *, 0}.

GEOSGeometry.touches(other)

Renvoie True si la matrice d’intersection DE-9IM des deux objets géométriques est FT*******, F**T***** ou F***T****.

GEOSGeometry.within(other)

Renvoie True si la matrice d’intersection DE-9IM des deux objets géométriques est T*F**F***.

Méthodes topologiques

GEOSGeometry.buffer(width, quadsegs=8)

Renvoie un objet GEOSGeometry représentant tous les points dont la distance à cet objet géométrique est plus petit ou égal à la longueur width donnée. Le paramètre facultatif quadsegs définit le nombre de segments utilisés pour faire l’approximation d’un quart de cercle (8 par défaut).

GEOSGeometry.buffer_with_style(width, quadsegs=8, end_cap_style=1, join_style=1, mitre_limit=5.0)

Identique à buffer(), mais permet de personnaliser le style du tampon.

  • end_cap_style peut être rond (1), plat (2) ou carré (3).

  • join_style peut être rond (1), onglet (2) ou biseau (3).

  • La limite de taux d’onglet (mitre_limit) n’affecte que le style de jointure par onglet.

GEOSGeometry.difference(other)

Renvoie un objet GEOSGeometry représentant les points composants cet objet géométrique qui ne composent pas l’autre objet.

GEOSGeometry.interpolate(distance)
GEOSGeometry.interpolate_normalized(distance)

Étant donné une distance (nombre à virgule), renvoie le point (ou le point le plus proche) de l’objet géométrique (LineString ou MultiLineString) à cette distance. La version normalisée accepte une distance sous forme d’un nombre à virgule entre 0 (origine) et 1 (point terminal).

Inverse de GEOSGeometry.project().

GEOSGeometry.intersection(other)

Renvoie un objet GEOSGeometry représentant les points partagés entre cet objet géométrique et l’objet other.

GEOSGeometry.project(point)
GEOSGeometry.project_normalized(point)

Renvoie la distance (nombre à virgule) à partir de l’origine de l’objet géométrique (LineString ou MultiLineString) jusqu’au point projeté sur la géométrie (c’est-à-dire le point de la ligne le plus proche du point donné). La version normalisée renvoie la distance sous forme d’un nombre à virgule entre 0 (origine) et 1 (point terminal).

Inverse de GEOSGeometry.interpolate().

GEOSGeometry.relate(other)

Renvoie la matrice d’intersection DE-9IM (une chaîne) représentant la relation topologique entre cet objet géométrique et l’objet en paramètre.

GEOSGeometry.simplify(tolerance=0.0, preserve_topology=False)

Renvoie un nouvel objet GEOSGeometry, simplifié à la tolérance indiquée en utilisant l’algorithme Douglas-Peucker. Une plus haute valeur de tolérance produit moins de points dans le résultat. Si aucune tolérance n’est fournie, la valeur par défaut est 0.

Par défaut, cette fonction ne préserve pas la topologie. Par exemple, les objets Polygon peuvent être divisés, être fusionnés pour former des lignes ou carrément disparaître. Des trous de Polygon peuvent apparaître ou disparaître et des lignes peuvent se croiser. En définissant preserve_topology=True, le résultat aura les mêmes dimensions et le même nombre de composants que l’objet de départ ; la fonction est cependant nettement plus lente.

GEOSGeometry.sym_difference(other)

Renvoie un objet GEOSGeometry formé des points de cet objet géométrique qui ne sont pas dans l’objet en paramètre, ainsi que des points dans l’objet en paramètre qui ne sont pas dans cet objet.

GEOSGeometry.union(other)

Renvoie un objet GEOSGeometry représentant tous les points de cet objet géométrique additionnés de ceux de l’objet en paramètre.

Propriétés topologiques

GEOSGeometry.boundary

Renvoie les limites sous forme d’une nouvelle instance d’objet géométrique.

GEOSGeometry.centroid

Returns a Point object representing the geometric center of the geometry. The point is not guaranteed to be on the interior of the geometry.

GEOSGeometry.convex_hull

Renvoie le plus petit Polygon contenant tous les points de l’objet géométrique.

GEOSGeometry.envelope

Renvoie un Polygon qui représente l’enveloppe englobante de cet objet géométrique. Notez qu’un Point peut aussi être renvoyé si l’objet en entrée est lui-même un point.

GEOSGeometry.point_on_surface

Calcule et renvoie un Point assuré d’être à l’intérieur de l’objet géométrique.

GEOSGeometry.unary_union

Calcule l’union de tous les éléments de cet objet géométrique.

Le résultat respecte le contrat suivant :

  • L’union d’un ensemble de LineString procède à leur complète mise en nœuds et à la dissolution des lignes.

  • L’union d’un ensemble de Polygon renvoie toujours un objet géométrique Polygon ou MultiPolygon (au contraire de GEOSGeometry.union() qui peut renvoyer des géométries de plus faible dimension si un conflit de topologie se produit).

Autres propriétés et méthodes

GEOSGeometry.area

Cette propriété renvoie l’aire de l’objet géométrique.

GEOSGeometry.extent

Cette propriété renvoie l’étendue de cet objet géométrique sous forme d’un tuple à 4 éléments, formé de (xmin, ymin, xmax, ymax).

GEOSGeometry.clone()

Cette méthode renvoie un objet GEOSGeometry clone de l’original.

GEOSGeometry.distance(geom)

Renvoie la distance entre les points les plus proches de cet objet géométrique et l’objet geom (un autre objet GEOSGeometry).

Note

Les calculs de distance GEOS sont linéaires ; en d’autres termes, GEOS n’effectue pas de calculs sphériques même si le SRID définit un système de coordonnées géographique.

GEOSGeometry.length

Renvoie la longueur de cet objet géométrique (par ex. 0 pour un Point, la longueur d’une ligne LineString ou la circonférence d’un Polygon).

GEOSGeometry.prepared

Renvoie un objet GEOS PreparedGeometry relatif au contenu de cet objet géométrique. Les objets PreparedGeometry sont optimisés pour les opérations contains, intersects, covers, crosses, disjoint, overlaps, touches et within. Référez-vous à la documentation Objets géométriques préparés pour plus d’informations.

GEOSGeometry.srs

Renvoie un objet SpatialReference correspondant au SRID de l’objet géométrique ou .

GEOSGeometry.transform(ct, clone=False)

Transforme l’objet géométrique en fonction du paramètre de transformation de coordonnées donné (ct), qui peut être un numéro de SRID, une chaîne de référence spatiale WKT, une chaîne PROJ, un objet SpatialReference ou un objet CoordTransform. Par défaut, l’objet géométrique est transformé lui-même et rien n’est renvoyé. Cependant, quand le paramètre clone est défini, l’objet géométrique n’est pas modifié et c’est un clone transformé de l’objet géométrique qui est renvoyé.

Note

Génère une exception GEOSException si GDAL n’est pas disponible ou si la valeur SRID de l’objet géométrique est None ou plus petite que 0. Aucune contrainte n’est imposée pour le code SRID de l’objet géométrique quand elle est appelée avec un objet CoordTransform.

GEOSGeometry.make_valid()

Renvoie un équivalent GEOSGeometry valable, en essayant de ne perdre aucune caractéristique géométrique de l’objet en entrée. Si ce dernier est déjà valable, il est renvoyé non modifié. C’est similaire à la fonction de base de données MakeValid. Nécessite GEOS 3.8.

GEOSGeometry.normalize(clone=False)

Convertit cet objet géométrique sous sa forme canonique. Si le paramètre clone est défini, l’objet n’est pas touché et un clone normalisé est renvoyé à la place :

>>> g = MultiPoint(Point(0, 0), Point(2, 2), Point(1, 1))
>>> print(g)
MULTIPOINT (0 0, 2 2, 1 1)
>>> g.normalize()
>>> print(g)
MULTIPOINT (2 2, 1 1, 0 0)

Point

class Point(x=None, y=None, z=None, srid=None)[source]

Les objets Point sont créés en utilisant des paramètres représentant les composantes de coordonnées du point ou une suite unique de coordonnées. Par exemple, les lignes suivantes sont équivalentes :

>>> pnt = Point(5, 23)
>>> pnt = Point([5, 23])

Des objets Point vides peuvent être instanciés en ne passant aucun paramètre ou une liste vide. Ces lignes sont équivalentes :

>>> pnt = Point()
>>> pnt = Point([])

LineString

class LineString(*args, **kwargs)[source]

Les objets LineString sont créés en utilisant des paramètres représentant une suite de coordonnées ou une suite d’objets Point. Par exemple, les lignes suivantes sont équivalentes :

>>> ls = LineString((0, 0), (1, 1))
>>> ls = LineString(Point(0, 0), Point(1, 1))

De plus, les objets LineString peuvent aussi être créés en passant une seule liste de coordonnées ou d’objets Point:

>>> ls = LineString(((0, 0), (1, 1)))
>>> ls = LineString([Point(0, 0), Point(1, 1)])

Des objets LineString vides peuvent être instanciés en ne passant aucun paramètre ou une liste vide. Ces lignes sont équivalentes :

>>> ls = LineString()
>>> ls = LineString([])
closed

Indique si cette ligne LineString est fermée.

LinearRing

class LinearRing(*args, **kwargs)[source]

Les objets LinearRing sont construits de la même manière que les objets LineString. Cependant, les coordonnées doivent être fermées, c’est-à-dire que la première et la dernière coordonnée doivent être identiques. Par exemple :

>>> ls = LinearRing((0, 0), (0, 1), (1, 1), (0, 0))

Remarquez que (0, 0) est à la fois la première et la dernière coordonnée ; si elles ne sont pas égales, une erreur est générée.

is_counterclockwise[source]

Indique si cet objet LinearRing est orienté dans le sens antihoraire.

Polygon

class Polygon(*args, **kwargs)[source]

Polygon objects may be instantiated by passing in parameters that represent the rings of the polygon. The parameters must either be LinearRing instances, or a sequence that may be used to construct a LinearRing:

>>> ext_coords = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))
>>> int_coords = ((0.4, 0.4), (0.4, 0.6), (0.6, 0.6), (0.6, 0.4), (0.4, 0.4))
>>> poly = Polygon(ext_coords, int_coords)
>>> poly = Polygon(LinearRing(ext_coords), LinearRing(int_coords))
classmethod from_bbox(bbox)[source]

Renvoie un objet polygone à partir du rectangle englobant donné, un tuple à 4 éléments comprenant (xmin, ymin, xmax, ymax).

num_interior_rings[source]

Renvoie le nombre de segments intérieurs de cet objet géométrique.

Comparaison de polygones

Notez qu’il est possible de comparer des objets Polygon directement avec < or >, mais comme la comparaison se fait à travers les segments LineString du polygone, cela n’a pas grande signification (mais c’est cohérent et rapide). Vous pouvez toujours forcer la comparaison avec la propriété area:

>>> if poly_1.area > poly_2.area:
...     pass
...

Collections géométriques

MultiPoint

class MultiPoint(*args, **kwargs)[source]

Les objets MultiPoint peuvent être créés en passant des objets Point en paramètres ou une seule liste d’objets Point:

>>> mp = MultiPoint(Point(0, 0), Point(1, 1))
>>> mp = MultiPoint((Point(0, 0), Point(1, 1)))

MultiLineString

class MultiLineString(*args, **kwargs)[source]

Les objets MultiLineString peuvent être créés en passant des objets LineString en paramètres ou une seule liste d’objets LineString:

>>> ls1 = LineString((0, 0), (1, 1))
>>> ls2 = LineString((2, 2), (3, 3))
>>> mls = MultiLineString(ls1, ls2)
>>> mls = MultiLineString([ls1, ls2])
merged

Renvoie une ligne LineString représentant la fusion de tous les composants de cet objet

closed

Renvoie True si et seulement si tous les éléments sont fermés.

MultiPolygon

class MultiPolygon(*args, **kwargs)[source]

Les objets MultiPolygon peuvent être créés en passant des objets Polygon en paramètres ou une seule liste d’objets Polygon:

>>> p1 = Polygon(((0, 0), (0, 1), (1, 1), (0, 0)))
>>> p2 = Polygon(((1, 1), (1, 2), (2, 2), (1, 1)))
>>> mp = MultiPolygon(p1, p2)
>>> mp = MultiPolygon([p1, p2])

GeometryCollection

class GeometryCollection(*args, **kwargs)[source]

Les objets GeometryCollection peuvent être créés en passant des objets GEOSGeometry en paramètres ou une seule liste d’objets GEOSGeometry:

>>> poly = Polygon(((0, 0), (0, 1), (1, 1), (0, 0)))
>>> gc = GeometryCollection(Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly)
>>> gc = GeometryCollection((Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly))

Objets géométriques préparés

In order to obtain a prepared geometry, access the GEOSGeometry.prepared property. Once you have a PreparedGeometry instance its spatial predicate methods, listed below, may be used with other GEOSGeometry objects. An operation with a prepared geometry can be orders of magnitude faster – the more complex the geometry that is prepared, the larger the speedup in the operation. For more information, please consult the GEOS wiki page on prepared geometries.

Par exemple :

>>> from django.contrib.gis.geos import Point, Polygon
>>> poly = Polygon.from_bbox((0, 0, 5, 5))
>>> prep_poly = poly.prepared
>>> prep_poly.contains(Point(2.5, 2.5))
True

PreparedGeometry

class PreparedGeometry

Toutes les méthodes des objets PreparedGeometry acceptent un paramètre other (autre) qui doit représenter une instance GEOSGeometry.

contains(other)
contains_properly(other)
covers(other)
crosses(other)
disjoint(other)
intersects(other)
overlaps(other)
touches(other)
within(other)

Fabrication d’objets géométriques

fromfile(file_h)[source]
Paramètres:

file_h (a Python file object or a string path to the file) – Fichier d’entrée contenant des données spatiales

Type renvoyé:

un objet GEOSGeometry correspondant aux données spatiales du fichier

Exemple :

>>> from django.contrib.gis.geos import fromfile
>>> g = fromfile("/home/bob/geom.wkt")
fromstr(string, srid=None)[source]
Paramètres:
  • string (str) – chaîne contenant des données spatiales

  • srid (int) – identifiant de référence spatiale

Type renvoyé:

un objet GEOSGeometry correspondant aux données spatiales de la chaîne

fromstr(string, srid) est équivalente à GEOSGeometry(string, srid).

Exemple :

>>> from django.contrib.gis.geos import fromstr
>>> pnt = fromstr("POINT(-90.5 29.5)", srid=4326)

Objets d’entrées/sorties

Objets de lecture

Les classes d’entrées/sorties en lecture renvoient une instance GEOSGeometry à partir du contenu WKB ou WKT en entrée en fonction de leur méthode read(geom).

class WKBReader[source]

Exemple :

>>> from django.contrib.gis.geos import WKBReader
>>> wkb_r = WKBReader()
>>> wkb_r.read("0101000000000000000000F03F000000000000F03F")
<Point object at 0x103a88910>
class WKTReader[source]

Exemple :

>>> from django.contrib.gis.geos import WKTReader
>>> wkt_r = WKTReader()
>>> wkt_r.read("POINT(1 1)")
<Point object at 0x103a88b50>

Objets d’écriture

All writer objects have a write(geom) method that returns either the WKB or WKT of the given geometry. In addition, WKBWriter objects also have properties that may be used to change the byte order, and or include the SRID value (in other words, EWKB).

class WKBWriter(dim=2)[source]

WKBWriter provides the most control over its output. By default it returns OGC-compliant WKB when its write method is called. However, it has properties that allow for the creation of EWKB, a superset of the WKB standard that includes additional information. See the WKBWriter.outdim documentation for more details about the dim argument.

write(geom)[source]

Renvoie la représentation WKB de l’objet géométrique sous forme d’objet Python buffer. Exemple :

>>> from django.contrib.gis.geos import Point, WKBWriter
>>> pnt = Point(1, 1)
>>> wkb_w = WKBWriter()
>>> wkb_w.write(pnt)
<read-only buffer for 0x103a898f0, size -1, offset 0 at 0x103a89930>
write_hex(geom)[source]

Returns WKB of the geometry in hexadecimal. Example:

>>> from django.contrib.gis.geos import Point, WKBWriter
>>> pnt = Point(1, 1)
>>> wkb_w = WKBWriter()
>>> wkb_w.write_hex(pnt)
'0101000000000000000000F03F000000000000F03F'
byteorder

Cette propriété peut être définie pour changer l’ordre des octets de la représentation géométrique.

Valeur byteorder

Description

0

Gros-boutiste (big endian, compatible avec les systèmes RISC)

1

Petit-boutiste (little endian, compatible avec les systèmes x86)

Exemple :

>>> from django.contrib.gis.geos import Point, WKBWriter
>>> wkb_w = WKBWriter()
>>> pnt = Point(1, 1)
>>> wkb_w.write_hex(pnt)
'0101000000000000000000F03F000000000000F03F'
>>> wkb_w.byteorder = 0
'00000000013FF00000000000003FF0000000000000'
outdim[source]

This property may be set to change the output dimension of the geometry representation. In other words, if you have a 3D geometry then set to 3 so that the Z value is included in the WKB.

Valeur outdim

Description

2

Par défaut, produit du contenu WKB en 2D.

3

Produit du contenu WKB en 3D.

Exemple :

>>> from django.contrib.gis.geos import Point, WKBWriter
>>> wkb_w = WKBWriter()
>>> wkb_w.outdim
2
>>> pnt = Point(1, 1, 1)
>>> wkb_w.write_hex(pnt)  # By default, no Z value included:
'0101000000000000000000F03F000000000000F03F'
>>> wkb_w.outdim = 3  # Tell writer to include Z values
>>> wkb_w.write_hex(pnt)
'0101000080000000000000F03F000000000000F03F000000000000F03F'
srid[source]

Set this property with a boolean to indicate whether the SRID of the geometry should be included with the WKB representation. Example:

>>> from django.contrib.gis.geos import Point, WKBWriter
>>> wkb_w = WKBWriter()
>>> pnt = Point(1, 1, srid=4326)
>>> wkb_w.write_hex(pnt)  # By default, no SRID included:
'0101000000000000000000F03F000000000000F03F'
>>> wkb_w.srid = True  # Tell writer to include SRID
>>> wkb_w.write_hex(pnt)
'0101000020E6100000000000000000F03F000000000000F03F'
class WKTWriter(dim=2, trim=False, precision=None)[source]

Cette classe permet de produire la représentation WKT d’un objet géométrique. Voir les attributs WKBWriter.outdim, trim et precision pour plus de détails sur les paramètres du constructeur.

write(geom)[source]

Renvoie la représentation WKT de l’objet géométrique. Exemple :

>>> from django.contrib.gis.geos import Point, WKTWriter
>>> pnt = Point(1, 1)
>>> wkt_w = WKTWriter()
>>> wkt_w.write(pnt)
'POINT (1.0000000000000000 1.0000000000000000)'
outdim[source]

Voir WKBWriter.outdim.

trim[source]

Cette propriété est utilisée pour activer ou désactiver la suppression de décimales non nécessaires.

>>> from django.contrib.gis.geos import Point, WKTWriter
>>> pnt = Point(1, 1)
>>> wkt_w = WKTWriter()
>>> wkt_w.trim
False
>>> wkt_w.write(pnt)
'POINT (1.0000000000000000 1.0000000000000000)'
>>> wkt_w.trim = True
>>> wkt_w.write(pnt)
'POINT (1 1)'
precision[source]

Cette propriété contrôle la précision de l’arrondi des coordonnées ; si elle vaut None, l’arrondi est désactivé.

>>> from django.contrib.gis.geos import Point, WKTWriter
>>> pnt = Point(1.44, 1.66)
>>> wkt_w = WKTWriter()
>>> print(wkt_w.precision)
None
>>> wkt_w.write(pnt)
'POINT (1.4399999999999999 1.6599999999999999)'
>>> wkt_w.precision = 0
>>> wkt_w.write(pnt)
'POINT (1 2)'
>>> wkt_w.precision = 1
>>> wkt_w.write(pnt)
'POINT (1.4 1.7)'

Notes de bas de page

Réglages

GEOS_LIBRARY_PATH

A string specifying the location of the GEOS C library. Typically, this setting is only used if the GEOS C library is in a non-standard location (e.g., /home/bob/lib/libgeos_c.so).

Note

Le réglage doit contenir le chemin complet vers la bibliothèque partagée en C ; en d’autres termes, il faut indiquer libgeos_c.so, et non pas libgeos.so.

Exceptions

exception GEOSException[source]

L’exception GEOS de base, indiquant une erreur en lien avec GEOS.