Skip to content

Instantly share code, notes, and snippets.

@pbabik
Forked from bmcbride/postgis_geojson.php
Created March 21, 2012 10:22
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save pbabik/2146017 to your computer and use it in GitHub Desktop.
Save pbabik/2146017 to your computer and use it in GitHub Desktop.
PHP PostGIS to GeoJSON - with BBOX query
<?php
/**
* PostGIS to GeoJSON
* Query a PostGIS table or view and return the results in GeoJSON format, suitable for use in OpenLayers, Leaflet, etc.
*
* @param string $bbox Bounding box of request *REQUIRED*
* @param string $geotable The PostGIS layer name *REQUIRED*
* @param string $geomfield The PostGIS geometry field *REQUIRED*
* @param string $srid The SRID of the returned GeoJSON *OPTIONAL (If omitted, EPSG: 4326 will be used)*
* @param string $fields Fields to be returned *OPTIONAL (If omitted, all fields will be returned)* NOTE- Uppercase field names should be wrapped in double quotes
* @param string $parameters SQL WHERE clause parameters *OPTIONAL*
* @param string $orderby SQL ORDER BY constraint *OPTIONAL*
* @param string $sort SQL ORDER BY sort order (ASC or DESC) *OPTIONAL*
* @param string $limit Limit number of results returned *OPTIONAL*
* @param string $offset Offset used in conjunction with limit *OPTIONAL*
* @return string resulting geojson string
*/
$dbconn = pg_connect ("host=localhost port=5432 dbname=db user=user password=pass");
if (!$dbconn) {
echo("Error in connection: " . pg_last_error());
}
$bbox = $_GET['bbox'];
list($bbox_west, $bbox_south, $bbox_east, $bbox_north) = split(",", $bbox);
if (empty($_GET['geotable'])) {
echo "missing required parameter: <i>geotable</i>";
exit;
} else
$geotable = $_GET['geotable'];
if (empty($_GET['geomfield'])) {
echo "missing required parameter: <i>geomfield</i>";
exit;
} else
$geomfield = $_GET['geomfield'];
if (empty($_GET['srid'])) {
$srid = '4326';
} else
$srid = $_GET['srid'];
if (empty($_GET['fields'])) {
$fields = '*';
} else
$fields = $_GET['fields'];
$parameters = $_GET['parameters'];
$orderby = $_GET['orderby'];
if (empty($_GET['sort'])) {
$sort = 'ASC';
} else
$sort = $_GET['sort'];
$limit = $_GET['limit'];
$offset = $_GET['offset'];
# Build SQL SELECT statement and return the geometry as a GeoJSON element in EPSG: 4326
$sql = "SELECT " . pg_escape_string($fields) . ", st_asgeojson(transform(" . pg_escape_string($geomfield) . ",$srid)) AS geojson FROM " . pg_escape_string($geotable);
if (strlen(trim($parameters)) > 0) {
$sql .= " WHERE " . pg_escape_string($parameters);
$sql .= " AND (box(point(" . $bbox_west . "," . $bbox_south . "),point(" . $bbox_east . "," . $bbox_north . ")) ~ (". $geomfield ."))";
}
else {
$sql .= " WHERE (box(point(" . $bbox_west . "," . $bbox_south . "),point(" . $bbox_east . "," . $bbox_north . ")) ~ (". $geomfield ."))";
}
if (strlen(trim($orderby)) > 0) {
$sql .= " ORDER BY " . pg_escape_string($orderby) . " " . $sort;
}
if (strlen(trim($limit)) > 0) {
$sql .= " LIMIT " . pg_escape_string($limit);
}
if (strlen(trim($offset)) > 0) {
$sql .= " OFFSET " . pg_escape_string($offset);
}
$sql .= ";";
//echo $sql;
# Try query or error
$rs = pg_query($dbconn, $sql);
if (!$rs) {
echo "An SQL error occured.\n";
exit;
}
# Build GeoJSON
#$output = '';
#$rowOutput = '';
$geojson = array(
'type' => 'FeatureCollection',
'features' => array()
);
while($row=pg_fetch_assoc($rs)) {
$properties = array();
foreach ($row as $key => $val) {
if ($key != 'geojson') {
// array_push($properties,$key,$val);
$properties[$key] = $val;
};
};
$feature = array(
'type' => 'Feature',
'properties' => $properties,
'geometry' => json_decode($row['geojson'], true),
);
// Add feature array to feature collection array
array_push($geojson['features'], $feature);
}
// Close database connection
pg_close($dbconn);
//header('Content-type: application/json',true);
echo json_encode($geojson);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment