-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathsqlite_geojson.php
54 lines (47 loc) · 1.62 KB
/
sqlite_geojson.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
/**
* Title: SQLite to GeoJSON (Requires https://github.com/phayes/geoPHP)
* Notes: Query a SQLite table or view (with a WKB GEOMETRY field) and return the results in GeoJSON format, suitable for use in OpenLayers, Leaflet, etc. Use QGIS to OGR to convert your GIS data to SQLite.
* Author: Bryan R. McBride, GISP
* Contact: bryanmcbride.com
* GitHub: https://github.com/bmcbride/PHP-Database-GeoJSON
*/
# Include required geoPHP library and define wkb_to_json function
include_once('geoPHP/geoPHP.inc');
function wkb_to_json($wkb) {
$geom = geoPHP::load($wkb,'wkb');
return $geom->out('json');
}
# Connect to SQLite database
$conn = new PDO('sqlite:mydatabase.sqlite');
# Build SQL SELECT statement and return the geometry as a GeoJSON element
$sql = 'SELECT *, GEOMETRY AS wkb FROM mytable';
# Try query or error
$rs = $conn->query($sql);
if (!$rs) {
echo 'An SQL error occured.\n';
exit;
}
# Build GeoJSON feature collection array
$geojson = array(
'type' => 'FeatureCollection',
'features' => array()
);
# Loop through rows to build feature arrays
while ($row = $rs->fetch(PDO::FETCH_ASSOC)) {
$properties = $row;
# Remove wkb and geometry fields from properties
unset($properties['wkb']);
unset($properties['GEOMETRY']);
$feature = array(
'type' => 'Feature',
'geometry' => json_decode(wkb_to_json($row['wkb'])),
'properties' => $properties
);
# Add feature arrays to feature collection array
array_push($geojson['features'], $feature);
}
header('Content-type: application/json');
echo json_encode($geojson, JSON_NUMERIC_CHECK);
$conn = NULL;
?>