如何从mysql空间表输出geoJSON文件?

时间:2016-10-04 13:15:27

标签: mysql geojson

我有一个表(' pk')的mysql空间数据库(' mydb1'),我是使用ogr2​​ogr工具从点shapefile获得的。这一行的一行' pk'表,就像:

 OGR_FID   SHAPE       CODIF    Position_X   Position_Y    Nom   Status
 1     [GEOMETRY-25o]  PAC182854  398235.38    414569.24    G-31   Vert

我需要输出该表的geoJSON文件。我下载了geoPHP库,并使用MySQL到GeoJSON脚本,我根据我的设置进行了调整,如下所示:

<?php
/**
* Title:   MySQL to GeoJSON (Requires https://github.com/phayes/geoPHP)
* Notes:   Query a MySQL table or view and return the results in GeoJSON format, suitable for use in OpenLayers, Leaflet, etc.
* 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 MySQL database
$conn = new PDO('mysql:host=localhost;dbname=mydb1','root','admin');

# Build SQL SELECT statement and return the geometry as a WKB element
$sql = 'SELECT *, AsWKB(SHAPE) AS wkb FROM pk';

# 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['SHAPE']);
    $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;
?>

但是当我在浏览器上执行代码时,我完全得到一个空白页面。我应该修复输出我的geoJSON文件的错误?

1 个答案:

答案 0 :(得分:-1)

如果出现错误,您应该检查php日志以获取更多信息。确保启用错误报告和显示:

error_reporting(E_ALL);
ini_set('display_errors', 1);

如果没有出现错误,请检查最简单的$ geojson对象

print_r($geojson);