-
-
Save AABoyles/b52a2a7ecd2575aeb880 to your computer and use it in GitHub Desktop.
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 | |
/** | |
* 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 $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 | |
*/ | |
if (empty($_GET['geomfield'])) { | |
echo "missing required parameter: <i>geomfield</i>"; | |
exit; | |
} else { | |
$geomfield = $_GET['geomfield']; | |
} | |
$srid = '4326'; | |
if (!empty($_GET['srid'])) { | |
$srid = $_GET['srid']; | |
} | |
$fields = '*'; | |
if (!empty($_GET['fields'])) { | |
$fields = $_GET['fields']; | |
} | |
$parameters = $_GET['parameters']; | |
$orderby = $_GET['orderby']; | |
$sort = 'ASC'; | |
if (!empty($_GET['sort'])) { | |
$sort = $_GET['sort']; | |
} | |
$limit = $_GET['limit']; | |
$offset = $_GET['offset']; | |
# Connect to PostgreSQL database | |
$conn = pg_connect("dbname='mydbname' user='myusername' password='mypassword' host='localhost'"); | |
if (!$conn) { | |
echo "Not connected : " . pg_error(); | |
exit; | |
} | |
$sql = "SELECT $fields, st_asgeojson(transform($geomfield, $srid)) AS geojson FROM events"); | |
if (strlen(trim($parameters)) > 0) { $sql .= " WHERE $parameters"; } | |
if (strlen(trim($orderby)) > 0) { $sql .= " ORDER BY $orderby $sort"; } | |
if (strlen(trim($limit)) > 0) { $sql .= " LIMIT $limit"; } | |
if (strlen(trim($offset)) > 0) { $sql .= " OFFSET $offset"; } | |
$sql = pg_escape_string($sql); | |
# Try query or error | |
$rs = pg_query($conn, $sql); | |
if (!$rs) { | |
echo "An SQL error occured.\n"; | |
exit; | |
} | |
$output = array( | |
'type' => 'FeatureCollection', | |
'features' => array() | |
); | |
while ($row = pg_fetch_assoc($rs)) { | |
$output['features'][] = array( | |
'type' => 'Feature', | |
'geometry' => $row['geojson'], | |
'properties' => $row, | |
'id' => $row['id'] | |
) | |
} | |
echo json_encode($output); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment