Skip to main content

Geo functions

Ember Nexus adds functions for geo values to Expr Lang. They are available in schema rules, in the sources of embeddings, in the expressions of search steps and in the playground.

Geometries are GeoJSON objects of one of the six geometry types which schemas support: Point, LineString, Polygon, MultiPoint, MultiLineString and MultiPolygon. Rules see the values of geo properties in this form, also when the request sent WKT. Every function starts with geo, so the names do not clash with the builtins and operators of Expr Lang (contains is an operator, len a builtin).

Semantics

  • Predicates are planar: geoIntersects, geoDisjoint, geoContains and geoWithin treat longitude and latitude as plane coordinates, like the geo_shape queries of Elasticsearch, and so do geoBbox and geoCentroid. The edges of a geometry are straight lines on a map in the equirectangular projection; a line from longitude 179 to -179 runs through the whole map, not across the antimeridian.
  • Measurements are geodesic: geoDistance, geoWithinDistance, geoLength and geoArea calculate on a sphere with the mean radius of the Earth (6,371,008.8 meters), the model of the arc distances of Elasticsearch and of MongoDB’s 2dsphere queries. Results are in meters and square meters. A segment is the shortest way between its positions, so a segment from longitude 179 to -179 crosses the antimeridian and is 2 degrees long. Line strings are measured this way everywhere, e.g. the line from 179 to -179 touches the point (180, 0) and is 179 degrees away from (0, 0), although the planar geoIntersects sees it the other way round.
  • Polygon edges must span less than 180 degrees of longitude in measurements: the predicates read an edge from -170 to 170 as 340 degrees wide, on the sphere it is the short way of 20 degrees across the antimeridian, and an edge from -180 to 180 along a latitude (e.g. of a cap around a pole) has no length at all. Area, length and distance of such a polygon would contradict geoContains, so the measurements fail for it instead. Split a polygon across the antimeridian at longitude 180 into a multi polygon, its parts then have the same meaning for predicates and measurements.
  • Altitudes are ignored by predicates and measurements. Only geoAlt, geoToWkt and geoIsValid look at them.
  • Invalid geometries are errors, which fail the expression, and with it the rule and the write. A geometry is valid if it has one of the six types, positions of 2 or 3 finite numbers (the same number in the whole geometry), longitudes from -180 to 180 and latitudes from -90 to 90, at least 2 distinct positions per line string, closed rings of at least 4 positions which do not intersect themselves, and follows the other rules of valid polygons and multi polygons of the OGC Simple Features standard (holes inside the exterior ring, polygons of a multi polygon do not overlap). Line strings may cross themselves. geoIsValid is the only function which accepts anything and never fails.
  • Inputs are limited: one call reads at most 1,000 positions, summed over its geometry arguments, configurable with expression.maxGeoPositions (see configuration). Larger inputs fail the expression. Values of geo properties are limited by the 16 MB of a MongoDB document anyway, the limit keeps rules fast enough for writes. The runtime of geoDistance grows with the product of the numbers of positions of both geometries.
  • Types are checked when an expression is compiled: arguments which are known to have the wrong type, e.g. a string instead of a geometry, are reported when a schema with the rule is saved. Values of properties are only known at runtime.

Buffers, unions, intersections, differences, simplification and convex hulls are not supported.

Creating and converting geometries

geoPoint

geoPoint(lon float, lat float[, alt float]) mapAvailable in schema rules, search expressions and the playground.

Returns a GeoJSON Point with the longitude, the latitude and optionally the altitude. Integers are accepted as well.

Errors: a longitude outside of -180 to 180 or a latitude outside of -90 to 90.

geoPoint(13.405, 52.52)
Result
{"type": "Point", "coordinates": [13.405, 52.52]}
geoPoint(13.405, 52.52, 34)
Result
{"type": "Point", "coordinates": [13.405, 52.52, 34]}
geoPoint(200, 0)
Error
the longitude 200 is outside of [-180, 180]

geoFromWkt

geoFromWkt(wkt string) mapAvailable in schema rules, search expressions and the playground.

Parses WKT into a GeoJSON geometry. It accepts what geo properties accept: keywords in any case, an optional Z marker, the prefix SRID=4326; and positions of a MULTIPOINT with and without parentheses.

Errors: invalid WKT, an SRID other than 4326, EMPTY geometries, GEOMETRYCOLLECTION, M coordinates and invalid geometries.

geoFromWkt('POINT (13.405 52.52)')
Result
{"type": "Point", "coordinates": [13.405, 52.52]}
geoFromWkt('SRID=4326;linestring z (0 0 10, 1 1 20)')
Result
{"type": "LineString", "coordinates": [[0, 0, 10], [1, 1, 20]]}
geoFromWkt('POINT EMPTY')
Error
empty geometries are not supported

geoToWkt

geoToWkt(g map) stringAvailable in schema rules, search expressions and the playground.

Returns the geometry as WKT, in the format of responses with Prefer: geometry=wkt: upper case keywords, Z for positions with altitude and every position of a MULTIPOINT in parentheses.

Errors: invalid geometries.

geoToWkt(geoPoint(13.405, 52.52, 34))
Result
"POINT Z (13.405 52.52 34)"
geoToWkt(document.area)
Variables
{
  "document": {
    "area": {
      "type": "Polygon",
      "coordinates": [[[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]]]
    }
  }
}
Result
"POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))"

Reading geometries

geoType

geoType(g map) stringAvailable in schema rules, search expressions and the playground.

Returns the GeoJSON type of the geometry, e.g. Polygon.

Errors: invalid geometries.

geoType(document.route)
Variables
{
  "document": {
    "route": {
      "type": "LineString",
      "coordinates": [[13.37, 52.51], [13.41, 52.52]]
    }
  }
}
Result
"LineString"

geoLon

geoLon(p map) floatAvailable in schema rules, search expressions and the playground.

Returns the longitude of a Point.

Errors: invalid geometries and other types than Point.

geoLon(geoPoint(13.405, 52.52))
Result
13.405

geoLat

geoLat(p map) floatAvailable in schema rules, search expressions and the playground.

Returns the latitude of a Point.

Errors: invalid geometries and other types than Point.

geoLat(geoPoint(13.405, 52.52))
Result
52.52

geoAlt

geoAlt(p map) floatAvailable in schema rules, search expressions and the playground.

Returns the altitude of a Point with three coordinates.

Errors: invalid geometries, other types than Point and points without altitude.

geoAlt(geoPoint(13.405, 52.52, 34))
Result
34
geoAlt(geoPoint(13.405, 52.52))
Error
the point has no altitude

geoBbox

geoBbox(g map) []floatAvailable in schema rules, search expressions and the playground.

Returns the bounding box [minLon, minLat, maxLon, maxLat], in the order of the bbox member of GeoJSON. The box is planar, altitudes are ignored.

Errors: invalid geometries.

geoBbox(geoFromWkt('LINESTRING (13.37 52.51, 13.41 52.53, 13.39 52.5)'))
Result
[13.37, 52.5, 13.41, 52.53]

geoCentroid

geoCentroid(g map) mapAvailable in schema rules, search expressions and the playground.

Returns the planar centroid as a Point: the center of mass of the area of polygons, of the length of line strings, and the mean of the positions of points. The centroid of a non-convex polygon can lie outside of it.

Errors: invalid geometries.

geoCentroid(geoFromWkt('POLYGON ((0 0, 4 0, 4 2, 0 2, 0 0))'))
Result
{"type": "Point", "coordinates": [2, 1]}

geoIsValid

geoIsValid(g any) boolAvailable in schema rules, search expressions and the playground.

Returns whether the value is a valid geometry, see semantics. It accepts every value, never fails and returns false for values which are no geometry at all, and for geometries with more positions than the limit.

Errors: none.

geoIsValid(geoPoint(13.405, 52.52))
Result
true
geoIsValid({type: 'Polygon', coordinates: [[[0, 0], [1, 1], [1, 0], [0, 1], [0, 0]]]})
Result
false
[geoIsValid('POINT (1 2)'), geoIsValid(nil), geoIsValid({type: 'Point', coordinates: [0, 91]})]
Result
[false, false, false]

Measuring

geoDistance

geoDistance(a map, b map) floatAvailable in schema rules, search expressions and the playground.

Returns the geodesic distance in meters between the closest points of two geometries. Geometries which cross or touch each other have the distance 0, and so have geometries inside of a polygon, e.g. a point (planar, like geoContains).

Errors: invalid geometries and polygons with an edge which spans 180 degrees of longitude or more (see semantics).

round(geoDistance(geoPoint(13.377704, 52.516275), geoPoint(13.409419, 52.520803)))
Result
2204
round(geoDistance(geoPoint(179.5, 0), geoPoint(-179.5, 0)))
Result
111195
geoDistance(geoFromWkt('POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))'), geoPoint(5, 5))
Result
0
geoDistance(geoPoint(180, 0), geoFromWkt('LINESTRING (179 0, -179 0)'))
Result
0

geoWithinDistance

geoWithinDistance(a map, b map, meters float) boolAvailable in schema rules, search expressions and the playground.

Returns whether the distance between the geometries is at most meters. It stops as soon as it found two points which are close enough, which is faster than comparing the result of geoDistance.

Errors: invalid geometries, polygons with an edge which spans 180 degrees of longitude or more (see semantics) and a distance which is not a number.

geoWithinDistance(document.location, geoPoint(13.405, 52.52), 5000)
Variables
{
  "document": {
    "location": {"type": "Point", "coordinates": [13.377704, 52.516275]}
  }
}
Result
true

geoLength

geoLength(g map) floatAvailable in schema rules, search expressions and the playground.

Returns the geodesic length in meters: the length of line strings, and the perimeter of polygons, including the rings of holes. Points have the length 0.

Errors: invalid geometries and polygons with an edge which spans 180 degrees of longitude or more (see semantics).

round(geoLength(geoFromWkt('LINESTRING (13.377704 52.516275, 13.409419 52.520803)')))
Result
2204
round(geoLength(geoFromWkt('LINESTRING (179 0, -179 0)')))
Result
222390

geoArea

geoArea(g map) floatAvailable in schema rules, search expressions and the playground.

Returns the geodesic area in square meters of polygons and multi polygons, without their holes. Other geometries have the area 0.

Errors: invalid geometries and polygons with an edge which spans 180 degrees of longitude or more (see semantics).

round(geoArea(geoFromWkt('POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))')) / 1000000)
Result
12364
round(geoArea(geoFromWkt('MULTIPOLYGON (((179.5 0, 180 0, 180 1, 179.5 1, 179.5 0)), ((-180 0, -179.5 0, -179.5 1, -180 1, -180 0)))')) / 1000000)
Result
12364
geoArea(document.area) <= 50000
Variables
{
  "document": {
    "area": {
      "type": "Polygon",
      "coordinates": [
        [
          [13.4, 52.5],
          [13.402, 52.5],
          [13.402, 52.501],
          [13.4, 52.501],
          [13.4, 52.5]
        ]
      ]
    }
  }
}
Result
true

Comparing geometries

The predicates follow the DE-9IM definitions of the OGC Simple Features standard, the relations of Elasticsearch’s geo_shape queries have the same names. They are planar. The boundary of a geometry is not part of its interior: a polygon does not contain a point on its edge, but intersects it.

geoIntersects

geoIntersects(a map, b map) boolAvailable in schema rules, search expressions and the playground.

Returns whether the geometries have at least one point in common, including their boundaries.

Errors: invalid geometries.

geoIntersects(geoFromWkt('POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))'), geoFromWkt('LINESTRING (-5 5, 15 5)'))
Result
true
geoIntersects(geoFromWkt('POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))'), geoPoint(0, 5))
Result
true

geoDisjoint

geoDisjoint(a map, b map) boolAvailable in schema rules, search expressions and the playground.

Returns whether the geometries have no point in common, the opposite of geoIntersects. A point in the hole of a polygon is disjoint from it.

Errors: invalid geometries.

geoDisjoint(geoFromWkt('POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0), (4 4, 6 4, 6 6, 4 6, 4 4))'), geoPoint(5, 5))
Result
true

geoContains

geoContains(a map, b map) boolAvailable in schema rules, search expressions and the playground.

Returns whether b lies inside of a: no point of b is outside of a, and the interiors have at least one point in common.

Errors: invalid geometries.

geoContains(document.area, document.location) ? true : 'the location must be inside of the area'
Variables
{
  "document": {
    "area": {
      "type": "Polygon",
      "coordinates": [[[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]]]
    },
    "location": {"type": "Point", "coordinates": [15, 5]}
  }
}
Result
"the location must be inside of the area"
geoContains(geoFromWkt('POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))'), geoPoint(0, 5))
Result
false

geoWithin

geoWithin(a map, b map) boolAvailable in schema rules, search expressions and the playground.

Returns whether a lies inside of b, the contains relation with swapped arguments.

Errors: invalid geometries.

geoWithin(geoPoint(2, 2), geoFromWkt('POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))'))
Result
true

Using geo functions in rules

A rule of a schema with the geo properties area (a polygon) and location (a point) which keeps the location inside of the area. Rules return true to accept a write; the string is the error message otherwise, see geo values in rules:

{
"expression": "document.location == nil || document.area == nil || geoContains(document.area, document.location) ? true : 'the location must be inside of the area'"
}

In a search, expressions can calculate geometries for queries, e.g. a bounding box around a point of the parameters, see parameters and expressions. The geospatial search examples show queries for points near a position and for areas which contain a point.