Skip to content

Instantly share code, notes, and snippets.

@mjfoster83
Last active June 7, 2020 05:34
Show Gist options
  • Save mjfoster83/b9a04232a1b5bfd6d868 to your computer and use it in GitHub Desktop.
Save mjfoster83/b9a04232a1b5bfd6d868 to your computer and use it in GitHub Desktop.
Dirt-Simple PostGIS HTTP Rest API: Get GeoJSON
<?php
/*
Get GeoJSON
Returns a GeoJSON from your table.
Based on:
https://github.com/bmcbride/PHP-Database-GeoJSON by Brian McBride
To be used with the Dirt-Simple PostGIS HTTP API:
https://github.com/tobinbradley/dirt-simple-postgis-http-api by @tobinbradley
*/
# Return header
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
# Includes
require("../inc/database.inc.php");
require("../inc/error_handler.inc.php");
# Time limit and error reporting level
# For debugging set error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
set_time_limit(5);
error_reporting(E_ERROR);
# Retrive URL arguments
$table = $_REQUEST['table'];
$fields = isset($_REQUEST['fields']) ? $_REQUEST['fields'] : '*';
$parameters = isset($_REQUEST['parameters']) ? " where " . $_REQUEST['parameters'] : '';
$order = isset($_REQUEST['order']) ? " order by " . $_REQUEST['order'] : '';
$limit = isset($_REQUEST['limit']) ? " limit " . $_REQUEST['limit'] : '';
# Perform the query
$sql = "select " . $fields . ", ST_AsGeoJSON(the_geom) as geojson FROM " . $table . $parameters . $order . $limit;
$db = pgConnection();
$statement=$db->prepare( $sql );
$statement->execute();
# Build GeoJSON feature collection array
$geojson = array(
'type' => 'FeatureCollection',
'features' => array()
);
# Loop through rows to build feature arrays
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$properties = $row;
# Remove geojson and geometry fields from properties
unset($properties['geojson']);
unset($properties['the_geom']);
$feature = array(
'type' => 'Feature',
'geometry' => json_decode($row['geojson'], true),
'properties' => $properties
);
# Add feature arrays to feature collection array
array_push($geojson['features'], $feature);
}
echo json_encode($geojson, JSON_PRETTY_PRINT);
$conn = NULL;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment