在 PHP (Laravel) 中将 Json 重新格式化为 geoJson

aib*_*rra 3 php json google-maps geojson laravel

我有 laravel 输出以下内容:

[
{
"id": 3,
"lat": "38.8978378",
"lon": "-77.0365123"
},
{
"id": 4,
"lat": "44.8",
"lon": "1.7"
},
{
"id": 22,
"lat": "37.59046",
"lon": "-122.348994"
}
]
Run Code Online (Sandbox Code Playgroud)

我希望它是 geoJson 格式:

{ "type": "FeatureCollection",
    "features": [
      { "type": "Feature",
        "geometry": {"type": "Point", "coordinates": [lat, lon]},
        "properties": {
         "name": "value"
         }
       }    
      ]
  }
Run Code Online (Sandbox Code Playgroud)

我知道我需要某种循环。但我不确定如何在 PHP 中构建它。任何指导将不胜感激。试图构建一个地图应用程序,它可以在世界视图上有几千个标记。我已经在考虑聚类,但需要通过这个基本步骤。

谢谢!

aib*_*rra 5

我修改了循环,安排有点偏离。如果有人感兴趣,可以把它变成一个函数:

function geoJson ($locales) 
    {
        $original_data = json_decode($locales, true);
        $features = array();

        foreach($original_data as $key => $value) { 
            $features[] = array(
                    'type' => 'Feature',
                    'geometry' => array('type' => 'Point', 'coordinates' => array((float)$value['lat'],(float)$value['lon'])),
                    'properties' => array('name' => $value['name'], 'id' => $value['id']),
                    );
            };   

        $allfeatures = array('type' => 'FeatureCollection', 'features' => $features);
        return json_encode($allfeatures, JSON_PRETTY_PRINT);

    }
Run Code Online (Sandbox Code Playgroud)