Generating GeoJSON in SQLite
GeoJSON is an open standard based on JSON to represent geographic features. It supports points, lines, polygons, and multipart collections of the previous feature types. This post demonstrates ways of leveraging point location data in a SQLite database as latitude and longitude and converting into GeoJSON for usage as a map layer. Given a SQLite locations table with the following schema:
1 | uuid TEXT |
and the data
column has the point location data with accuracy values in json format:
1 | { |
First let’s filter out any points with accuracy levels above a certain threshold, e.g. 25M, by using JSON parsing:
1 | SELECT * |
The json_extract(json(data), '$.additional.accuracy')
extracts the accuracy
value from the additional
object in the JSON data.
Now we want to format the existing JSON data in the data
column as GeoJSON. We can do this with the following query:
1 | SELECT |
This creates a GeoJSON feature object for each row which includes a point geometry and properties from the other columns. This results GeoJSON for each row in the table as individual points:
1 | { |
In order to create single GeoJSON file representing all of the rows in the table we need to use a Common Table Expression (CTE) with a subquery that creates individual GeoJSON feature objects for each point and wrap this in a GeoJSON FeatureCollection
:
1 | WITH point_features AS ( |
This results in a single row with one column named geojson_collection
containing a complete GeoJSON FeatureCollection
object with all rows in the table:
1 | { |
Copy the results into Sublime Text and view in a sample web view with MapPreview