Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Geography

rind reads and writes PostGIS columns: points, polygons and any other geometry. Queries can filter and order by distance, test whether a shape holds a point, and measure areas. An API can answer GeoJSON for a map.

This is what GeoDjango (django.contrib.gis) and djangorestframework-gis do for a Django application. rind covers the common part of it: geographic coordinates in WGS 84 (SRID 4326), stored as geography, with distances in metres.

The types are in rind::db::geo. The path methods come with the query layer.

Setting up the database

The database needs the postgis extension. The domain whose models have geographic columns asks for it in its migrations:

#![allow(unused)]
fn main() {
// sample/crates/network/network-models/src/lib.rs
pub fn migrations() -> rind::migrations::Domain {
    rind::migrations::domain!("network", schema()).extension("postgis")
}
}

The migrations then create the extension before the tables (Migrations).

Geographic columns

A geographic column is a field of one of the rind::db::geo types, with its SQL type given by sql. rind cannot choose the SQL type by itself: a point can be a geography or a geometry.

#![allow(unused)]
fn main() {
// sample/crates/network/network-models/src/lib.rs
pub struct Station {
    // …
    /// Where it is: a PostGIS point.
    #[column(sql = "geography(Point,4326)")]
    pub position: Option<rind::db::geo::Point>,
}

pub struct Region {
    // …
    /// Its outline: a PostGIS multipolygon, GeoJSON in the API.
    #[column(sql = "geography(MultiPolygon,4326)")]
    pub shape: Option<rind::db::geo::MultiPolygon>,
}
}

Use geography, as here. The query methods below compute on a geography, in metres, on the spheroid. This is GeoDjango’s PointField(geography=True).

There is a type for each kind of value:

TypeHoldsIn JSON
Pointa point{"lng": 2.3212, "lat": 48.8412}
Polygona polygonGeoJSON: {"type": "Polygon", "coordinates": [[[2.2, 48.8], …]]}
MultiPolygona multipolygonGeoJSON: {"type": "MultiPolygon", "coordinates": [[[[2.2, 48.8], …]]]}
Geometryany geometry: points, lines, polygons, their multiples, collectionsany GeoJSON geometry
Shapeany PostGIS value, kept byte for byteits EWKB, in hexadecimal

A Point is sent as an object with lng and lat, which is easier to read in an API than GeoJSON’s [lng, lat]. The shapes are sent as GeoJSON geometries. Shape is for a value that must come back exactly as it was read, whatever it holds.

How values are read and written

rind reads the values as PostGIS sends them, in EWKB (or ISO WKB), from a geography or a geometry column. A third and a fourth coordinate (Z and M) are read and dropped. Values are written with the SRID 4326.

What a client may send

A shape that a client sends is checked before the database sees it:

  • every longitude is between -180 and 180, every latitude between -90 and 90;
  • a line has two positions or more;
  • a ring of a polygon has four positions or more, and is closed (its last position is its first).

A wrong shape is the field’s error, and says what is wrong:

PATCH /regions/2
{"shape": ["A ring has four positions or more, its last one its first."]}

A value that is not a GeoJSON geometry is refused in the same way. A geometry of another kind than the field’s (a polygon sent to a MultiPolygon field) is refused too, with the general “Invalid value.”.

A Point sent as {"lng": …, "lat": …} is not checked by rind yet: a longitude or a latitude out of range is sent to the database as it is.

Querying by distance and by shape

A path to a geographic column has methods that give conditions and values. A station near a point is the most common case:

#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/filters.rs
/// `near=lng,lat,km`; a value that is not three numbers matches nothing.
pub fn near(q: Query<Station>, value: &str) -> Query<Station> {
    let numbers: Vec<f64> = value
        .split(',')
        .filter_map(|n| n.trim().parse().ok())
        .collect();
    match numbers.as_slice() {
        [lng, lat, km] => q.filter(Station::position().within_meters(*lng, *lat, km * 1000.0)),
        _ => q.filter(Station::id().eq(-1)),
    }
}
}

This is the method of a filter, so a client asks for it in the query string:

GET /stations?near=2.3212,48.8412,400

The answer has the stations at most 400 km from the point. In the sample’s tests, where Paris Montparnasse and Rennes are given a position, these are the two stations it lists. A row without a position does not match.

within_meters is GeoDjango’s dwithin lookup. It is written with PostGIS’s ST_DWithin, which a GiST index on the column serves. rind does not make that index by itself; declare it on the model: #[index(name = "network_station_position_idx", sql = "USING gist (position)")].

The methods

MethodWhat it givesGeoDjango
within_meters(lng, lat, m)a condition: at most m metres from the pointdwithin, distance_lte
distance_to(lng, lat)a value: the distance to the point, in metresDistance("position", point)
within_meters_of(other, m)a condition: at most m metres from another columndwithin with an F()
distance(other)a value: the distance to another column, in metresDistance("a", "b")
covers(lng, lat)a condition: the shape holds the pointcovers, contains
area()a value: the shape’s area, in square metres (0 for a point or a line)Area("shape")
centroid()a value: the shape’s centroid, as a pointCentroid("shape")
is_point(lng, lat)a condition: the point is exactly this oneposition=point

A value (a distance, an area) is null when a column is null. It is an expression like any other: it is selected, compared, and ordered by.

#![allow(unused)]
fn main() {
// Stations by distance from a point, the nearest first.
Query::<Station>::new()
    .filter(Station::position().is_not_null())
    .order_by([Station::position().distance_to(2.3212, 48.8412).asc()])
}

Between two columns

The other column can be reached through relations, so the length of a journey, from its origin to its destination as the crow flies, is one expression. A serializer sends it when it is asked for:

#![allow(unused)]
fn main() {
// sample/crates/timetable/timetable-api/src/journeys/serializers.rs
/// From its origin to its destination as the crow flies, in metres.
#[annotated(
    expr = Journey::origin().position().distance(Journey::destination().position()),
    on_request
)]
pub distance: Option<Option<f64>>,
}

A filter on it is just as short:

#![allow(unused)]
fn main() {
// sample/crates/timetable/timetable-api/src/journeys/filters.rs
/// `min_km`: origin and destination further apart than this.
pub fn longer_than(q: Query<Journey>, km: f64) -> Query<Journey> {
    q.filter(!Journey::origin().position().within_meters_of(Journey::destination().position(), km * 1000.0))
}
}

Shapes that hold a point

A region whose outline holds a point:

#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/regions.rs
q.filter(Region::shape().covers(lng, lat))
}

The railway answers it as GET /regions?covers=lng,lat, and sends each region’s area when it is asked for (#[annotated(expr = Region::shape().area(), on_request)]).

A centroid, and an exact point

shape.centroid() is a shape’s centroid, as a point. It is GEOS’s centroid (Django’s poly.centroid), computed on the coordinates. Its type is the point type of the column it is written to, so it fits in an update:

#![allow(unused)]
fn main() {
// a model with a polygon `shape` and a point `position`
db.execute(&Update::<Town>::new()
    .set(Town::position(), Town::shape().centroid())
    .filter(Town::position().is_null()))
    .await?;
}

position.is_point(lng, lat) matches a row at that point exactly (Django’s filter(position=point)). A row without a point does not match.

Other PostGIS functions

The methods above are the common ones. Another PostGIS function is written in SQL where an operation needs it (ST_ConcaveHull, ST_Union), with db.query_sql (Queries). Inside a typed query, rind::query::func::call calls a function of one argument, and rind::query::Expr::Func takes any function with any arguments.

GeoJSON answers

A map wants a layer: a GeoJSON FeatureCollection, one feature per object. rind::db::geo::Feature and FeatureCollection write it, as Django’s rest_framework_gis does with its GeoFeatureModelSerializer:

  • a feature has the object’s id beside its type;
  • its geometry is a Point, a Polygon, or any Geometry, as a GeoJSON geometry, or null when the object has none;
  • its other values are in properties, added with .with(name, value).

An action answers it. The railway maps the stations that the list would show:

#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/views.rs
#[action(GET, cached)]
pub async fn geojson(ctx: &Ctx, params: &QueryParams) -> Result<FeatureCollection, ApiError> {
    let query = rind::api::resource::list_query::<StationResource>(ctx, (), params)?;
    let select = query
        .select((Station::id(), Station::name(), Station::status(), Station::position()))
        .into_select();
    let rows: Vec<(i64, String, String, Option<Point>)> = ctx.db.rows(&select).await?;
    Ok(FeatureCollection::new(
        rows.into_iter()
            .map(|(id, name, status, position)| {
                Feature::new(id, position).with("name", name).with("status", status)
            })
            .collect(),
    ))
}
}
GET /stations/geojson?status=open

The answer has this shape (a station without a position has "geometry": null):

{"type": "FeatureCollection", "features": [
  {"id": 1, "type": "Feature",
   "geometry": {"type": "Point", "coordinates": [2.3212, 48.8412]},
   "properties": {"name": "Paris Montparnasse", "status": "open"}},
  …
]}

In a feature, a point is a GeoJSON geometry, [lng, lat], and not the {"lng", "lat"} object of an ordinary answer: this is what map libraries read.

To put two layers in one answer, chain them: stations.chain(depots) is a collection with the features of both.

What is not handled yet

  • A list answered as a GeoJSON feature collection by the list itself (?format=geojson) will come with the exports. Until then, write an action, as above.
  • Geometries in another SRID than 4326, rasters and topologies are not handled.
  • GeoDjango’s other lookups (intersects, within, overlaps, touches…) and functions have no method yet: write them in SQL.

Reference

Types of rind::db::geo

TypeColumnJSON in and out
Point { lng, lat }geography(Point,4326), or a geometry point{"lng": …, "lat": …}
Polygongeography(Polygon,4326)a GeoJSON Polygon
MultiPolygongeography(MultiPolygon,4326)a GeoJSON MultiPolygon
Geometryany geography or geometryany GeoJSON geometry
Shapeany PostGIS valueits EWKB in hexadecimal
Feature(an answer)a GeoJSON Feature
FeatureCollection(an answer)a GeoJSON FeatureCollection

Position is [f64; 2], a longitude and a latitude, in GeoJSON’s order.

Path methods

MethodOnSQL
within_meters(lng, lat, m)any geographic columnST_DWithin(col, point, m)
distance_to(lng, lat)any geographic columnST_Distance(col, point)
within_meters_of(other, m)any geographic columnST_DWithin(col, other, m)
distance(other)any geographic columnST_Distance(col, other)
covers(lng, lat)any geographic columnST_Covers(col, point)
area()any geographic columnST_Area(col)
centroid()any geographic columnST_Centroid(col::geometry)::geography
is_point(lng, lat)a point columnST_Equals(col::geometry, point::geometry)

The point (lng, lat) is sent as ST_GeogFromText('SRID=4326;POINT(lng lat)').