or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

database-administration.mdindex.mdmigration-support.mdshapely-integration.mdspatial-elements.mdspatial-functions.mdspatial-types.md

spatial-functions.mddocs/

0

# Spatial Functions

1

2

Comprehensive library of 376+ spatial functions covering geometry construction, spatial relationships, measurements, transformations, and raster operations. Functions are dynamically generated and provide consistent interfaces across all supported database backends.

3

4

## Function Usage Patterns

5

6

Spatial functions can be called in multiple ways:

7

8

```python

9

from geoalchemy2 import functions as func

10

from sqlalchemy.sql import func as sql_func

11

12

# Using geoalchemy2.functions module

13

result = session.query(func.ST_Area(Lake.geom)).scalar()

14

15

# Using SQLAlchemy's func object

16

result = session.query(sql_func.ST_Area(Lake.geom)).scalar()

17

18

# Applying to spatial elements directly

19

lake = session.query(Lake).first()

20

area = lake.geom.ST_Area()

21

22

# In query filters

23

large_lakes = session.query(Lake).filter(

24

func.ST_Area(Lake.geom) > 1000000

25

).all()

26

```

27

28

## Capabilities

29

30

### Geometry Construction Functions

31

32

Create geometries from coordinates, existing geometries, and other spatial data sources.

33

34

```python { .api }

35

def ST_MakePoint(x: float, y: float, z: float = None, m: float = None):

36

"""Create a 2D, 3DZ or 4D Point."""

37

38

def ST_MakePointM(x: float, y: float, m: float):

39

"""Create a Point from X, Y and M values."""

40

41

def ST_MakeLine(*points):

42

"""Create a Linestring from Point, MultiPoint, or LineString geometries."""

43

44

def ST_MakePolygon(shell, holes=None):

45

"""Create a Polygon from a shell and optional list of holes."""

46

47

def ST_MakeEnvelope(xmin: float, ymin: float, xmax: float, ymax: float, srid: int = None):

48

"""Create a rectangular Polygon from minimum and maximum coordinates."""

49

50

def ST_Collect(*geometries):

51

"""Create a GeometryCollection or Multi* geometry from a set of geometries."""

52

53

def ST_Point(x: float, y: float):

54

"""Create a Point with the given coordinate values. Alias for ST_MakePoint."""

55

56

def ST_Polygon(linestring, srid: int = None):

57

"""Create a Polygon from a LineString with a specified SRID."""

58

59

def ST_LineFromMultiPoint(multipoint):

60

"""Create a LineString from a MultiPoint geometry."""

61

```

62

63

Usage examples:

64

65

```python

66

from geoalchemy2.functions import ST_MakePoint, ST_MakeLine, ST_MakePolygon

67

68

# Create points

69

point1 = ST_MakePoint(0, 0)

70

point2 = ST_MakePoint(1, 1)

71

point3d = ST_MakePoint(0, 0, 10)

72

73

# Create line from points

74

line = ST_MakeLine(point1, point2)

75

76

# Create polygon from coordinates

77

envelope = ST_MakeEnvelope(-1, -1, 1, 1, 4326)

78

79

# Use in queries

80

nearby_points = session.query(Location).filter(

81

func.ST_DWithin(Location.geom, ST_MakePoint(0, 0), 1000)

82

).all()

83

```

84

85

### Geometry Accessors

86

87

Extract information and components from existing geometries.

88

89

```python { .api }

90

def ST_X(geom):

91

"""Return the X coordinate of a Point."""

92

93

def ST_Y(geom):

94

"""Return the Y coordinate of a Point."""

95

96

def ST_Z(geom):

97

"""Return the Z coordinate of a Point."""

98

99

def ST_M(geom):

100

"""Return the M coordinate of a Point."""

101

102

def ST_SRID(geom):

103

"""Return the spatial reference identifier for a geometry."""

104

105

def ST_GeometryType(geom):

106

"""Return the geometry type as a string."""

107

108

def ST_Dimension(geom):

109

"""Return the coordinate dimension of a geometry."""

110

111

def ST_CoordDim(geom):

112

"""Return the coordinate dimension of a geometry."""

113

114

def ST_NumGeometries(geom):

115

"""Return the number of geometries in a GeometryCollection."""

116

117

def ST_GeometryN(geom, n: int):

118

"""Return the Nth geometry in a GeometryCollection."""

119

120

def ST_NumPoints(geom):

121

"""Return the number of points in a LineString or CircularString."""

122

123

def ST_PointN(geom, n: int):

124

"""Return the Nth point in a LineString."""

125

126

def ST_StartPoint(geom):

127

"""Return the first point of a LineString."""

128

129

def ST_EndPoint(geom):

130

"""Return the last point of a LineString."""

131

132

def ST_Boundary(geom):

133

"""Return the boundary of a geometry."""

134

135

def ST_Envelope(geom):

136

"""Return the bounding box of a geometry."""

137

138

def ST_ExteriorRing(geom):

139

"""Return the exterior ring of a Polygon."""

140

141

def ST_NumInteriorRings(geom):

142

"""Return the number of interior rings in a Polygon."""

143

144

def ST_InteriorRingN(geom, n: int):

145

"""Return the Nth interior ring of a Polygon."""

146

```

147

148

### Spatial Relationships

149

150

Test spatial relationships between geometries using standardized predicates.

151

152

```python { .api }

153

def ST_Contains(geom1, geom2):

154

"""Test if geom1 completely contains geom2."""

155

156

def ST_Within(geom1, geom2):

157

"""Test if geom1 is completely within geom2."""

158

159

def ST_Intersects(geom1, geom2):

160

"""Test if two geometries intersect."""

161

162

def ST_Crosses(geom1, geom2):

163

"""Test if two geometries cross each other."""

164

165

def ST_Overlaps(geom1, geom2):

166

"""Test if two geometries overlap."""

167

168

def ST_Touches(geom1, geom2):

169

"""Test if two geometries touch at their boundaries."""

170

171

def ST_Disjoint(geom1, geom2):

172

"""Test if two geometries are disjoint (do not intersect)."""

173

174

def ST_Equals(geom1, geom2):

175

"""Test if two geometries are spatially equal."""

176

177

def ST_Covers(geom1, geom2):

178

"""Test if geom1 covers geom2."""

179

180

def ST_CoveredBy(geom1, geom2):

181

"""Test if geom1 is covered by geom2."""

182

183

def ST_ContainsProperly(geom1, geom2):

184

"""Test if geom1 properly contains geom2."""

185

186

def ST_Relate(geom1, geom2, pattern: str = None):

187

"""Test spatial relationship using DE-9IM intersection matrix."""

188

```

189

190

Usage examples:

191

192

```python

193

# Find buildings within a district

194

buildings_in_district = session.query(Building).filter(

195

func.ST_Within(Building.geom, district.geom)

196

).all()

197

198

# Find intersecting roads and railways

199

intersections = session.query(Road, Railway).filter(

200

func.ST_Intersects(Road.geom, Railway.geom)

201

).all()

202

203

# Complex spatial query with multiple predicates

204

complex_query = session.query(Parcel).filter(

205

func.ST_Contains(Parcel.geom, point),

206

func.ST_Area(Parcel.geom) > 1000,

207

~func.ST_Overlaps(Parcel.geom, flood_zone.geom) # NOT overlaps

208

).all()

209

```

210

211

### Distance and Measurement Functions

212

213

Calculate distances, areas, lengths, and other geometric measurements.

214

215

```python { .api }

216

def ST_Distance(geom1, geom2):

217

"""Calculate the minimum distance between two geometries."""

218

219

def ST_DWithin(geom1, geom2, distance: float):

220

"""Test if two geometries are within a specified distance."""

221

222

def ST_Area(geom):

223

"""Calculate the area of a polygon or multi-polygon."""

224

225

def ST_Length(geom):

226

"""Calculate the length of a linestring or multi-linestring."""

227

228

def ST_Perimeter(geom):

229

"""Calculate the perimeter of a polygon."""

230

231

def ST_Distance_Sphere(geom1, geom2):

232

"""Calculate spherical distance between two lon/lat geometries."""

233

234

def ST_Distance_Spheroid(geom1, geom2, spheroid: str):

235

"""Calculate distance on a spheroid between two geometries."""

236

237

def ST_Azimuth(geom1, geom2):

238

"""Calculate the azimuth between two points."""

239

240

def ST_Angle(geom1, geom2, geom3=None):

241

"""Calculate the angle between three points or two vectors."""

242

```

243

244

### Geometric Processing Functions

245

246

Transform, modify, and process geometries for analysis and visualization.

247

248

```python { .api }

249

def ST_Buffer(geom, distance: float, quadsegs: int = None):

250

"""Create a buffer around a geometry."""

251

252

def ST_Centroid(geom):

253

"""Calculate the centroid of a geometry."""

254

255

def ST_PointOnSurface(geom):

256

"""Return a point guaranteed to be on the surface of a geometry."""

257

258

def ST_Simplify(geom, tolerance: float):

259

"""Simplify a geometry using the Douglas-Peucker algorithm."""

260

261

def ST_SimplifyPreserveTopology(geom, tolerance: float):

262

"""Simplify a geometry while preserving topology."""

263

264

def ST_ConvexHull(geom):

265

"""Calculate the convex hull of a geometry."""

266

267

def ST_Union(*geometries):

268

"""Calculate the union of multiple geometries."""

269

270

def ST_Intersection(geom1, geom2):

271

"""Calculate the intersection of two geometries."""

272

273

def ST_Difference(geom1, geom2):

274

"""Calculate the difference between two geometries."""

275

276

def ST_SymDifference(geom1, geom2):

277

"""Calculate the symmetric difference between two geometries."""

278

279

def ST_Snap(geom1, geom2, tolerance: float):

280

"""Snap vertices of geom1 to geom2 within tolerance."""

281

282

def ST_SnapToGrid(geom, *args):

283

"""Snap geometry vertices to a grid."""

284

```

285

286

### Coordinate System Functions

287

288

Transform geometries between spatial reference systems and manage coordinate data.

289

290

```python { .api }

291

def ST_Transform(geom, srid: int):

292

"""Transform geometry to a different spatial reference system."""

293

294

def ST_SetSRID(geom, srid: int):

295

"""Set the SRID of a geometry without transformation."""

296

297

def ST_SRID(geom):

298

"""Return the SRID of a geometry."""

299

300

def Find_SRID(schema: str, table: str, column: str):

301

"""Find the SRID for a geometry column."""

302

303

def UpdateGeometrySRID(schema: str, table: str, column: str, srid: int):

304

"""Update the SRID of all features in a geometry column."""

305

```

306

307

### Input/Output Functions

308

309

Convert between different spatial data formats and representations.

310

311

```python { .api }

312

def ST_AsText(geom):

313

"""Return WKT representation of a geometry."""

314

315

def ST_AsEWKT(geom):

316

"""Return EWKT representation of a geometry."""

317

318

def ST_AsBinary(geom):

319

"""Return WKB representation of a geometry."""

320

321

def ST_AsEWKB(geom):

322

"""Return EWKB representation of a geometry."""

323

324

def ST_AsGeoJSON(geom, maxdecimaldigits: int = None):

325

"""Return GeoJSON representation of a geometry."""

326

327

def ST_AsKML(geom, maxdecimaldigits: int = None):

328

"""Return KML representation of a geometry."""

329

330

def ST_AsGML(geom, version: int = None):

331

"""Return GML representation of a geometry."""

332

333

def ST_AsSVG(geom, relative: bool = None, precision: int = None):

334

"""Return SVG representation of a geometry."""

335

336

def ST_GeomFromText(wkt: str, srid: int = None):

337

"""Create geometry from WKT representation."""

338

339

def ST_GeomFromWKB(wkb: bytes, srid: int = None):

340

"""Create geometry from WKB representation."""

341

342

def ST_GeomFromGeoJSON(geojson: str):

343

"""Create geometry from GeoJSON representation."""

344

345

def ST_GeomFromKML(kml: str):

346

"""Create geometry from KML representation."""

347

348

def ST_GeomFromGML(gml: str, srid: int = None):

349

"""Create geometry from GML representation."""

350

```

351

352

### Raster Functions

353

354

Process and analyze raster data including satellite imagery and elevation models.

355

356

```python { .api }

357

# Raster Information

358

def ST_Width(raster):

359

"""Return the width of a raster in pixels."""

360

361

def ST_Height(raster):

362

"""Return the height of a raster in pixels."""

363

364

def ST_NumBands(raster):

365

"""Return the number of bands in a raster."""

366

367

def ST_PixelWidth(raster):

368

"""Return the pixel width of a raster."""

369

370

def ST_PixelHeight(raster):

371

"""Return the pixel height of a raster."""

372

373

# Raster Values

374

def ST_Value(raster, band: int, x: int, y: int):

375

"""Return the value of a raster pixel."""

376

377

def ST_SetValue(raster, band: int, x: int, y: int, value: float):

378

"""Set the value of a raster pixel."""

379

380

def ST_BandNoDataValue(raster, band: int = None):

381

"""Return the NODATA value of a raster band."""

382

383

def ST_SetBandNoDataValue(raster, band: int, nodatavalue: float):

384

"""Set the NODATA value of a raster band."""

385

386

# Raster Processing

387

def ST_Clip(raster, geom):

388

"""Clip a raster by a geometry."""

389

390

def ST_Union(*rasters):

391

"""Union multiple rasters into a single raster."""

392

393

def ST_MapAlgebra(raster1, raster2, expression: str):

394

"""Apply map algebra expression to raster bands."""

395

396

def ST_Reclass(raster, reclassexpr: str):

397

"""Reclassify raster values using expressions."""

398

399

# Raster-Geometry Conversion

400

def ST_AsRaster(geom, *args):

401

"""Convert geometry to raster representation."""

402

403

def ST_DumpAsPolygons(raster, band: int = None):

404

"""Convert raster pixels to polygon geometries."""

405

406

def ST_ConvexHull(raster):

407

"""Return the convex hull of a raster."""

408

```

409

410

## Function Categories Summary

411

412

The complete function library includes:

413

414

- **Construction**: 15+ functions for creating geometries

415

- **Accessors**: 25+ functions for extracting geometry properties

416

- **Relationships**: 20+ functions for spatial predicates

417

- **Measurements**: 15+ functions for distances and areas

418

- **Processing**: 30+ functions for geometric operations

419

- **Coordinate Systems**: 10+ functions for SRID management

420

- **Input/Output**: 40+ functions for format conversion

421

- **Raster Operations**: 200+ functions for raster processing

422

- **Administrative**: 15+ functions for database management

423

424

All functions support:

425

- Consistent parameter interfaces across database backends

426

- Automatic type conversion and validation

427

- Integration with SQLAlchemy query expressions

428

- Direct application to spatial elements

429

- Proper error handling and exception reporting