SQLServer PHP 到 GeoJSON

SQLServer PHP to GeoJSON

正在尝试编写一个 PHP 页面,它将 return 来自 MS Sql 服务器的 GeoJSON。

ERROR msg: geometry member should be object, but is an String instead.

结果是什么:

[{"type":"Feature","geometry":"\"MULTILINESTRING ((-77.083060324719384 42.15108721847372, -77.087448024528669 42.151768518696542

我的代码:

$sql = "SELECT name, pwl_id, wbcatgry, basin, fact_sheet, geom.STAsText() as geo FROM dbo.total"; 

while ($res = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC)) {

    $str = $res['geo'];
    $wkt = explode("((",$str);

        $msg [] = array(
                    'type' => 'Feature',            
                    'geometry' => ($res['geo']),  //<<<---  where I'm stuck.
                    // 'geometry' => json_decode($res['geo'], true),

                    'properties' => array(
                    "PWL_ID" => $res['pwl_id'],
                    "Name" => $res['name'],

我在 MySQL 中使用

做到了这一点
ST_AsGeoJSON(`geom`) as geo and  'geometry' => json_decode($res['Geo'])  

但是SQL-服务器没有AsGeoJSON功能。

我想我可以获取地理文本并解析它并重新创建我需要的内容,但我希望有更好的方法,但我对解析代码不是 100% 确定。

输出如下:

{ "type": "Feature", "properties": { "PWL_ID": 18, "Name": "IN787", }, "geometry": { "type": "MultiLineString", "coordinates": [ [ [ -73.781598476340562, 42.633203605299833 ], [ -73.764907547494587, 42.63285861396318 ], [ -73.75312949415769, 42.639574643901661 ] .....

您可以使用 preg_match_all

解析它们
$string = "MULTILINESTRING ((-77.083060324719384 42.15108721847372, -77.087448024528669 42.151768518696542";

$pattern = '/((-?\d+\.\d+)\s(-?\d+\.\d+))/';

$arr = preg_match_all($pattern,$string,$matches);

print_r($matches);

输出

Array ( 
    [0] => Array (
        [0] => -77.083060324719384 42.15108721847372
        [1] => -77.087448024528669 42.151768518696542
    )
    [1] => Array (
        [0] => -77.083060324719384 42.15108721847372
        [1] => -77.087448024528669 42.151768518696542
    )
    [2] => Array (
        [0] => -77.083060324719384
        [1] => -77.087448024528669
    )
    [3] => Array (
        [0] => 42.15108721847372
        [1] => 42.151768518696542
    )
)

我以一种让您更容易使用结果的方式组织捕获,并且它只会匹配成对的坐标。

所以您需要的是项目 23。剩下的就很简单了。

但我决定表现得很好,

$len = count($matches[0]);
$coordinates = [];
for($i=0;$i<$len;++$i){
    $coordinates[] = [
        $matches[2][$i], $matches[3][$i]
    ];
}

print_r($coordinates);

输出

Array (
    [0] => Array (
        [0] => -77.083060324719384
        [1] => 42.15108721847372
    )
    [1] => Array (
        [0] => -77.087448024528669
        [1] => 42.151768518696542
    )
)

你可以在这里看到完整的交易

https://3v4l.org/ecLFJ

然后您应该可以将它插入您需要的地方,然后 json_encode 等等...

[["-77.083060324719384","42.15108721847372"],["-77.087448024528669","42.151768518696542"]]

当然,我只是在处理您在问题中提供的那一点点输入,但它可能有用。