如何将数据从 Laravel 数据库连接转换为 GeoJSON

How do I convert data from Laravel DB connection to GeoJSON

目前正在 Laravel 中制作一个使用 MapboxGLJS 的项目。我目前有一个连接到的数据库服务器,其中包含我需要将其转换为包含 ID 和空间数据的 GeoJSON FeatureCollection 的评论。我已经看到了执行此操作的代码示例,我将在下面提供,但是当我尝试使用所述代码并尝试使用 addSource Mapbox 方法时,它会返回 Error: Input data is not a valid GeoJSON object..

CommentController.php

...
public function all(){
      $comments = Comment::whereNotNull('user_id')->get();

        $mapFeatures = array();
        $mapFeatures['type'] = 'FeatureCollection';
        $mapFeatures['name'] = 'comments';
        $mapFeatures['crs'] = array(
            'type' => 'name',
            'properties' => array(
                'name' => 'urn:ogc:def:crs:OGC:1.3:CRS84'
            ),
        );
        $mapFeatures['features'] = array();

        foreach ($comments as $comment) {

            $mapItem = array(
                'type' => 'Feature',
                'properties' => array(
                    'id' => $comment->id,
                ),
                'geometry' => $comment->location
            );

            array_push($mapFeatures['features'], $mapItem);
        }

        return json_encode($mapFeatures);
    }
...

我使用 Postman 从 api 请求中收集了以下信息:

{
    "type": "FeatureCollection",
    "name": "comments",
    "crs": {
        "type": "name",
        "properties": {
            "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
        }
    },
    "features": [
        {
            "type": "Feature",
            "properties": {
                "id": 143
            },
            "geometry": "0101000020E6100000E17A14AE47E111C085EB51B81E054A40"
        },
        ...
    ]
}

运行 通过 https://geojsonlint.com/ 的数据返回 Line 1: old-style crs member is not recommended, this object is equivalent to the default and should be removed。还指出几何应该作为一个对象但是得到了一个字符串,我认为这与 crs 属性 没有正确解码几何有关。

是否需要其他 crs 才能正确解码几何图形? 不幸的是,我无法更改数据库中的数据以包含 lat/long 几何图形,因为当前数据正被另一个依赖于此格式的项目使用。

这个:

"0101000020E6100000E17A14AE47E111C085EB51B81E054A40"

不是 GeoJSON 几何图形。我不确定它到底是什么。它看起来像 PostGIS 的本机格式(参见 here),但我不知道它叫什么或如何在 PostGIS 之外从它转换。

GeoJSON 几何看起来像:

{
    "type": "LineString",
    "coordinates": [[...]]
}

如果您有权访问 PostGIS 查询,则应使用 ST_AsGeoJSON 函数。

这与 CRS 无关 - 该消息只是告诉您不要费心添加 crs 属性,假设您的数据在 EPSG:4326.

发现这里有专门解决此问题的软件包:

https://github.com/mstaack/laravel-postgis

只需要在获取坐标的Controller中安装引用即可