API version: 0.3.0

---

# Geo functions

Ember Nexus adds functions for geo values to [Expr Lang](/reference/formats-and-languages/expr-lang.md). They are
available in [schema rules](/reference/schemas/rules.md), in the sources of
[embeddings](/reference/schemas/types/vector.md#embeddings), in the expressions of
[search steps](/guide/search/parameters-and-expressions.md) and in the
[playground](/reference/formats-and-languages/expr-lang/playground.md).

Geometries are [GeoJSON](/reference/formats-and-languages/geojson.md) 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`](#geointersects), [`geoDisjoint`](#geodisjoint),
  [`geoContains`](#geocontains) and [`geoWithin`](#geowithin) treat longitude and latitude as plane coordinates, like
  the `geo_shape` queries of Elasticsearch, and so do [`geoBbox`](#geobbox) and [`geoCentroid`](#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`](#geodistance), [`geoWithinDistance`](#geowithindistance),
  [`geoLength`](#geolength) and [`geoArea`](#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`](#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`](#geoalt), [`geoToWkt`](#geotowkt) and
  [`geoIsValid`](#geoisvalid) look at them.
- **Invalid geometries are errors**, which fail the expression, and with it the [rule](/reference/schemas/rules.md) 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](https://en.wikipedia.org/wiki/Simple_Features) standard (holes inside
  the exterior ring, polygons of a multi polygon do not overlap). Line strings may cross themselves.
  [`geoIsValid`](#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](/reference/configuration.md)). 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`](#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]) map` - Available 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.

**Expression:**

```text
geoPoint(13.405, 52.52)
```

**Result:**

```json
{"type": "Point", "coordinates": [13.405, 52.52]}
```

**Expression:**

```text
geoPoint(13.405, 52.52, 34)
```

**Result:**

```json
{"type": "Point", "coordinates": [13.405, 52.52, 34]}
```

**Expression:**

```text
geoPoint(200, 0)
```

**Error:**

```text
the longitude 200 is outside of [-180, 180]
```

### geoFromWkt

`geoFromWkt(wkt string) map` - Available in schema rules, search expressions and the playground.

Parses [WKT](/reference/formats-and-languages/geojson.md#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.

**Expression:**

```text
geoFromWkt('POINT (13.405 52.52)')
```

**Result:**

```json
{"type": "Point", "coordinates": [13.405, 52.52]}
```

**Expression:**

```text
geoFromWkt('SRID=4326;linestring z (0 0 10, 1 1 20)')
```

**Result:**

```json
{"type": "LineString", "coordinates": [[0, 0, 10], [1, 1, 20]]}
```

**Expression:**

```text
geoFromWkt('POINT EMPTY')
```

**Error:**

```text
empty geometries are not supported
```

### geoToWkt

`geoToWkt(g map) string` - Available 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.

**Expression:**

```text
geoToWkt(geoPoint(13.405, 52.52, 34))
```

**Result:**

```json
"POINT Z (13.405 52.52 34)"
```

**Expression:**

```text
geoToWkt(document.area)
```

**Variables:**

```json
{
  "document": {
    "area": {
      "type": "Polygon",
      "coordinates": [[[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]]]
    }
  }
}
```

**Result:**

```json
"POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))"
```

## Reading geometries

### geoType

`geoType(g map) string` - Available in schema rules, search expressions and the playground.

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

**Errors**: invalid geometries.

**Expression:**

```text
geoType(document.route)
```

**Variables:**

```json
{
  "document": {
    "route": {
      "type": "LineString",
      "coordinates": [[13.37, 52.51], [13.41, 52.52]]
    }
  }
}
```

**Result:**

```json
"LineString"
```

### geoLon

`geoLon(p map) float` - Available in schema rules, search expressions and the playground.

Returns the longitude of a `Point`.

**Errors**: invalid geometries and other types than `Point`.

**Expression:**

```text
geoLon(geoPoint(13.405, 52.52))
```

**Result:**

```json
13.405
```

### geoLat

`geoLat(p map) float` - Available in schema rules, search expressions and the playground.

Returns the latitude of a `Point`.

**Errors**: invalid geometries and other types than `Point`.

**Expression:**

```text
geoLat(geoPoint(13.405, 52.52))
```

**Result:**

```json
52.52
```

### geoAlt

`geoAlt(p map) float` - Available 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.

**Expression:**

```text
geoAlt(geoPoint(13.405, 52.52, 34))
```

**Result:**

```json
34
```

**Expression:**

```text
geoAlt(geoPoint(13.405, 52.52))
```

**Error:**

```text
the point has no altitude
```

### geoBbox

`geoBbox(g map) []float` - Available 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.

**Expression:**

```text
geoBbox(geoFromWkt('LINESTRING (13.37 52.51, 13.41 52.53, 13.39 52.5)'))
```

**Result:**

```json
[13.37, 52.5, 13.41, 52.53]
```

### geoCentroid

`geoCentroid(g map) map` - Available 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.

**Expression:**

```text
geoCentroid(geoFromWkt('POLYGON ((0 0, 4 0, 4 2, 0 2, 0 0))'))
```

**Result:**

```json
{"type": "Point", "coordinates": [2, 1]}
```

### geoIsValid

`geoIsValid(g any) bool` - Available in schema rules, search expressions and the playground.

Returns whether the value is a valid geometry, see [semantics](#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](#semantics).

**Errors**: none.

**Expression:**

```text
geoIsValid(geoPoint(13.405, 52.52))
```

**Result:**

```json
true
```

**Expression:**

```text
geoIsValid({type: 'Polygon', coordinates: [[[0, 0], [1, 1], [1, 0], [0, 1], [0, 0]]]})
```

**Result:**

```json
false
```

**Expression:**

```text
[geoIsValid('POINT (1 2)'), geoIsValid(nil), geoIsValid({type: 'Point', coordinates: [0, 91]})]
```

**Result:**

```json
[false, false, false]
```

## Measuring

### geoDistance

`geoDistance(a map, b map) float` - Available 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`](#geocontains)).

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

**Expression:**

```text
round(geoDistance(geoPoint(13.377704, 52.516275), geoPoint(13.409419, 52.520803)))
```

**Result:**

```json
2204
```

**Expression:**

```text
round(geoDistance(geoPoint(179.5, 0), geoPoint(-179.5, 0)))
```

**Result:**

```json
111195
```

**Expression:**

```text
geoDistance(geoFromWkt('POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))'), geoPoint(5, 5))
```

**Result:**

```json
0
```

**Expression:**

```text
geoDistance(geoPoint(180, 0), geoFromWkt('LINESTRING (179 0, -179 0)'))
```

**Result:**

```json
0
```

### geoWithinDistance

`geoWithinDistance(a map, b map, meters float) bool` - Available in schema rules, search expressions and the playground.

Returns whether the [distance](#geodistance) 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](#semantics)) and a distance which is not a number.

**Expression:**

```text
geoWithinDistance(document.location, geoPoint(13.405, 52.52), 5000)
```

**Variables:**

```json
{
  "document": {
    "location": {"type": "Point", "coordinates": [13.377704, 52.516275]}
  }
}
```

**Result:**

```json
true
```

### geoLength

`geoLength(g map) float` - Available 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](#semantics)).

**Expression:**

```text
round(geoLength(geoFromWkt('LINESTRING (13.377704 52.516275, 13.409419 52.520803)')))
```

**Result:**

```json
2204
```

**Expression:**

```text
round(geoLength(geoFromWkt('LINESTRING (179 0, -179 0)')))
```

**Result:**

```json
222390
```

### geoArea

`geoArea(g map) float` - Available 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](#semantics)).

**Expression:**

```text
round(geoArea(geoFromWkt('POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))')) / 1000000)
```

**Result:**

```json
12364
```

**Expression:**

```text
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:**

```json
12364
```

**Expression:**

```text
geoArea(document.area) <= 50000
```

**Variables:**

```json
{
  "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:**

```json
true
```

## Comparing geometries

The predicates follow the [DE-9IM](https://en.wikipedia.org/wiki/DE-9IM) definitions of the OGC Simple Features
standard, the relations of Elasticsearch's `geo_shape` queries have the same names. They are [planar](#semantics). 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) bool` - Available 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.

**Expression:**

```text
geoIntersects(geoFromWkt('POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))'), geoFromWkt('LINESTRING (-5 5, 15 5)'))
```

**Result:**

```json
true
```

**Expression:**

```text
geoIntersects(geoFromWkt('POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))'), geoPoint(0, 5))
```

**Result:**

```json
true
```

### geoDisjoint

`geoDisjoint(a map, b map) bool` - Available in schema rules, search expressions and the playground.

Returns whether the geometries have no point in common, the opposite of [`geoIntersects`](#geointersects). A point in
the hole of a polygon is disjoint from it.

**Errors**: invalid geometries.

**Expression:**

```text
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:**

```json
true
```

### geoContains

`geoContains(a map, b map) bool` - Available 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.

**Expression:**

```text
geoContains(document.area, document.location) ? true : 'the location must be inside of the area'
```

**Variables:**

```json
{
  "document": {
    "area": {
      "type": "Polygon",
      "coordinates": [[[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]]]
    },
    "location": {"type": "Point", "coordinates": [15, 5]}
  }
}
```

**Result:**

```json
"the location must be inside of the area"
```

**Expression:**

```text
geoContains(geoFromWkt('POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))'), geoPoint(0, 5))
```

**Result:**

```json
false
```

### geoWithin

`geoWithin(a map, b map) bool` - Available in schema rules, search expressions and the playground.

Returns whether `a` lies inside of `b`, the [contains](#geocontains) relation with swapped arguments.

**Errors**: invalid geometries.

**Expression:**

```text
geoWithin(geoPoint(2, 2), geoFromWkt('POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))'))
```

**Result:**

```json
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](/reference/schemas/rules.md#geo-values):

```json
{
  "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](/guide/search/parameters-and-expressions.md). The
[geospatial search examples](/reference/search/elasticsearch-query-dsl-mixin/geospatial-search.md) show queries for
points near a position and for areas which contain a point.

---

Home: [Ember Nexus API docs](/index.md)

Full site map: [llms.txt](/llms.txt)

Previous: [Expr Lang](/reference/formats-and-languages/expr-lang.md)

Next: [Expr Lang playground](/reference/formats-and-languages/expr-lang/playground.md)
