Spatial data in the database

Places, routes and areas go into spatial columns with SRID 4326 (WGS 84, the coordinates of GPS and web maps) and are queried by box, by distance and by polygon through the same calls on every database:

DatabaseStorageMath
MySQL 8.0.3+POINT SRID 4326, GEOMETRY SRID 4326, SPATIAL indexgeographic; distance ST_Distance_Sphere
MariaDB 10.11+POINT REF_SYSTEM_ID=4326, SPATIAL indexplanar in degrees for boxes and polygons; distance ST_Distance_Sphere
PostgreSQL + PostGISgeography(Point,4326), GiST indexgeographic; distance ST_DWithin on the sphere
SQLitea point column pt is pt_lat / pt_lng DECIMAL(10,7); another spatial column geom is its GeoJSON text plus geom_min_lat, geom_min_lng, geom_max_lat, geom_max_lng box filter in SQL, distance (haversine) and point in polygon in PHP functions of the connection

Values go in and out as GeoJSON ([longitude, latitude], RFC 7946), so the latitude-first axis order of SRID 4326 WKT on MySQL never applies. Every value is checked (ranges, closed rings, at most 100,000 positions) and written into the SQL from numbers, so request data cannot reach the SQL text; a bad value throws InvalidArgumentException. The SQLite storage is meant for development, tests and small sites: it reads every row of the box.

A table

// share/db/sql_php/places.sql_php.php (fields of the vendor-neutral DDL)
'pt'   => ['name' => 'pt', 'type' => 'point', 'srid' => 4326, 'nullable' => false],
'area' => ['name' => 'area', 'type' => 'geometry', 'srid' => 4326, 'nullable' => true],
// indexes
'pt'   => ['name' => 'pt', 'type' => 'spatial', 'columns' => ['pt']],

Types: point, linestring, polygon, multipoint, multilinestring, multipolygon, geometrycollection, geometry (any of them), and json. MySQL needs NOT NULL and the SRID for the optimizer to use a spatial index. On PostgreSQL the columns are geography ('geo' => 'geometry' makes them planar geometry). The installer and db()->utils()->create_table() write the DDL of each database; a table with spatial columns is refused with the reason when the database has no spatial storage. add_column() refuses a spatial column on SQLite (it is several columns there).

Writing

$sp = db()->spatial();
$id = $sp->insert('places', ['name' => $name], ['pt' => ['lat' => 49.8397, 'lng' => 24.0297]]);
$sp->update('places', [], ['area' => $geojson_polygon], ['id' => $id]);    // where: column => value, never empty
// the SQL value of a point on MySQL / MariaDB / PostGIS, for your own statements:
$sql_value = db()->query_builder()->geo_point(49.8397, 24.0297);

A spatial value is a GeoJSON string, a decoded geometry (or Feature) array, or ['lat' => .., 'lng' => ..]. A plain list [lat, lng] is not accepted: GeoJSON puts the longitude first. insert() / update() escape the plain values themselves. On SQLite geo_point() throws: use values(), insert() or update().

Querying

// in the map view (west, south, east, north; west > east crosses the antimeridian)
$rows = db()->from('places')->select('id, name')->as_geojson('pt')
    ->where_bbox('pt', $w, $s, $e, $n)->limit(1000)->get_all();

// within 5 km, nearest first
$rows = db()->from('places')->select('id, name')->select_distance('pt', $lat, $lng, 'dist')
    ->where_distance('pt', $lat, $lng, 5000)->order_by('dist')->limit(20)->get_all();

// inside a polygon (GeoJSON Polygon or MultiPolygon)
$rows = db()->from('places')->select('id')->where_within('pt', $polygon)->get_all();

$point = yf_db_spatial::to_point($rows[0]['pt']);   // ['lat' => .., 'lng' => ..]
$geom = yf_db_spatial::decode($row['area']);         // the GeoJSON geometry as an array
  • where_distance() and select_distance() take point columns. The distance is on a sphere: MySQL, MariaDB and SQLite give the same metres, PostGIS differs by about 0.01 % (its own radius). where_distance() first narrows by the box around the circle, so the index is used.
  • where_bbox() matches shapes that touch the box. MariaDB and SQLite compare degrees on a plane, so they match exactly the box; MySQL 8 and PostGIS compute on the globe and get boxes of at most 90 degrees.
  • where_within() is planar on MariaDB (fine for city or country sized polygons); on SQLite a shape counts as within when all its vertices are.
  • Selecting a native spatial column without as_geojson() returns the database's binary form: always read through as_geojson().
  • SQLite: the helpers look the column layout up in the first table of from(); for a joined table pass the kind as the last argument ('point' or 'shape').

What the database offers

db()->spatial()->supported();   // 'native', 'decimal' (SQLite) or false
db()->spatial()->engine();      // mysql, mariadb, postgis, sqlite
db()->spatial()->error();       // why not, e.g. "PostGIS is not installed on the PostgreSQL server: ..."

The answer is probed once per connection. Without spatial storage the helpers throw RuntimeException with that reason; maps, tiles, form fields and geocoding of the maps plugin (separately distributed: install it) work without it.