Reformatting Json to geoJson in PHP (Laravel)

安稳与你 提交于 2019-12-05 20:54:32

I modified the loop, the arrangement was a bit off. And turned it into a function if anyone is interested:

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);

    }

Just use json_decode() on the original values and rebuild/reconstruct a new one. Consider this example:

$original_json_string = '[{"id": 3,"lat": "38.8978378","lon": "-77.0365123"},{"id": 4,"lat": "44.8","lon": "1.7"},{"id": 22,"lat": "37.59046","lon": "-122.348994"}]';
$original_data = json_decode($original_json_string, true);
$coordinates = array();
foreach($original_data as $key => $value) {
    $coordinates[] = array('lat' => $value['lat'], 'lon' => $value['lon']);
}
$new_data = array(
    'type' => 'FeatureCollection',
    'features' => array(
        'type' => 'Feature',
        'geometry' => array('type' => 'Point', 'coordinates' => $coordinates),
        'properties' => array('name' => 'value'),
    ),
);

$final_data = json_encode($new_data, JSON_PRETTY_PRINT);

print_r($final_data);

$final_data should yield something like:

{
    "type": "FeatureCollection",
    "features": {
        "type": "Feature",
        "geometry": {
            "type": "Point",
            "coordinates": [
                {
                    "lat": "38.8978378",
                    "lon": "-77.0365123"
                },
                {
                    "lat": "44.8",
                    "lon": "1.7"
                },
                {
                    "lat": "37.59046",
                    "lon": "-122.348994"
                }
            ]
        },
        "properties": {
            "name": "value"
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!