Created
October 25, 2014 16:01
-
-
Save pbabik/e03d0a9256d20368afa1 to your computer and use it in GitHub Desktop.
PHP PostGIS to GeoJSON - using JSON functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** Super Lazy PHP PostGIS to GeoJSON | |
* @originalAuthors Leo Hsu and Regina Obe | |
* @url http://www.postgresonline.com/journal/archives/267-Creating-GeoJSON-Feature-Collections-with-JSON-and-PostGIS-functions.html | |
* @phpImplementation pbabik <https://github.com/pbabik> | |
* @license WTFPL 2 <http://www.wtfpl.net/txt/copying/> | |
* @requires PostgreSQL 9.3 && PostGIS 2.1 or higher | |
**/ | |
//DB configuration | |
$host = 'localhost'; | |
$port = 5432; | |
$user = 'superuser'; | |
$pass = 'superpassword'; | |
$db = 'superdb'; | |
//connect to the DB | |
$pdo = new PDO("pgsql:host=$host;port=$port;dbname=$db;user=$user;password=$pass"); | |
//get query parameters with some basic protection against SQL Injection | |
$table = pg_escape_string($_GET['table']) or die('Missing required parameter: table'); | |
$srid = intval(isset($_GET['srid']) ? $_GET['srid'] : 4326); | |
//get non-geometry column names | |
$col_query = "SELECT string_agg('\"'|| column_name::text || '\"',',') FROM information_schema.columns WHERE table_name = '$table'"; | |
$col_query .=" AND column_name NOT IN(SELECT f_geometry_column FROM geometry_columns WHERE f_table_name = '$table')"; | |
$cols = $pdo->query($col_query)->fetch()[0]; | |
//get data as GeometryCollection | |
$data_query = "SELECT row_to_json(fc) FROM ( SELECT 'FeatureCollection' As type, array_to_json(array_agg(f)) As features"; | |
$data_query .= " FROM (SELECT 'Feature' As type"; | |
$data_query .= ", ST_AsGeoJSON(ST_Transform(lg.geom,$srid))::json As geometry"; | |
$data_query .= ", row_to_json(lp) As properties"; | |
$data_query .=" FROM \"$table\" As lg"; | |
$data_query .= " INNER JOIN (SELECT $cols FROM \"$table\") As lp"; | |
$data_query .= " ON lg.id = lp.id ) As f ) As fc"; | |
$data = $pdo->query($data_query)->fetch()[0]; | |
header('Content-Type: application/json'); | |
echo $data; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment