PHP GeoJSON 格式

PHP formatting for GeoJSON

正在尝试使用 PHP 为 GeoJSON(多边形)的几何部分格式化数据

$sql = "SELECT ST_AsGeoJSON(`geom`) as Geo FROM `usa` WHERE 1";

Returns 条类似的记录:

{"type": "Polygon", "coordinates": [[[-101.4073933...

到目前为止,我的代码尝试了 3 种不同的方式来格式化几何块,但都失败了。:

while ($res = mysqli_fetch_array($result,MYSQLI_ASSOC)) {

$msg [] = array(
        'type' => 'Feature',

        'geometry' => 
            $res['Geo'],
         /// ERROR  "geometry" member should be object, but is an String instead
        //"geometry":"{\"type\": \"Polygon\", \"coordinates\": [[[-104.05361517875079, 41.698


        'geometry' => array(
            $res['Geo'],
        ),   ///ERROR "geometry" member should be object, but is an Array instead
        //"geometry":["{\"type\": \"Polygon\", \"coordinates\": [[[-104.05361517875079, 41.6


        'geometry' => array(
            'type' => $res['Geo'].['type'],
            'coordinates' => $res['Geo'].['coordinates'],
        ),  
        //"geometry":{"type":"{\"type\": \"Polygon\", \"coordinates\": [[[[-122.4020155875262, 48.22521

它最终应该看起来像这样:

"geometry": { "type": "Polygon", "coordinates": [[[  -73.3450469

ST_AsGeoJSONreturns,顾名思义,JSON。这意味着 $res['Geo'] 是一个字符串,一个 JSON 字符串,代表一个 GeoJSON 对象。如果将该字符串放入稍后 json_encode 的 PHP 数组中,您将生成字符串的 JSON 编码。你想要的是一个数组或对象,然后你可以 json_encode 并且它将成为 JSON 中的对象,而不是字符串。

所以,JSON-解码你从数据库中得到的值得到一个PHP对象:

$msg[] = array(
    'type' => 'Feature',
    'geometry' => json_decode($res['Geo']),
    ...
);

JSON-encoding $msg 之后,它看起来像:

"geometry": {"type": "Polygon", "coordinates": ...}