PHP构建GeoJSON FeatureCollection结构时的格式问题求助
我最近在PHP里生成标准GeoJSON的FeatureCollection结构时卡壳了,先给大家看我想要的正确格式:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [102.0, 0.5]
},
"properties": {
"prop0": "value0"
}
}
]
}
但我自己跑出来的JSON格式完全不对,是这个样子的:
{
"type": "FeaturedCollection",
"0": {
"features": {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": []
}
},
"properties": {
"id": 282
}
},
"1": {
"features": {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": []
}
},
"properties": {
"id": 280
}
}
}
我一开始写的PHP代码是这样的:
foreach($posts as $post) { $data[] = array ( 'features' => array ( 'type' => 'Feature', 'geometry' => array ( 'type' => 'Point', 'coordinates' => array ( ), ), ), 'properties' => array( 'id' => $post->ID, ), ); } return $data;
后来我终于摸清楚正确的写法了,分享给有同样困扰的朋友:
核心问题是我之前搞反了结构层级——应该先搭好FeatureCollection的架子,再把每个Feature对象逐个塞进features数组里,而不是把每个Feature包装成带features键的元素。
完整的正确PHP代码示例:
// 示例数据(比如从数据库拉取的位置信息) $locations = array( array("name" => "Location A", "latitude" => 34.0522, "longitude" => -118.2437), array("name" => "Location B", "latitude" => 40.7128, "longitude" => -74.0060), ); // 先初始化GeoJSON的FeatureCollection基础结构 $geojson = array( 'type' => 'FeatureCollection', 'features' => array() ); // 遍历数据生成每个Feature对象,再加入到features数组中 foreach ($locations as $location) { $feature = array( 'type' => 'Feature', 'geometry' => array( 'type' => 'Point', // 注意GeoJSON的坐标顺序是:经度在前,纬度在后! 'coordinates' => array($location['longitude'], $location['latitude']) ), 'properties' => array( 'name' => $location['name'] // 可以根据业务需求添加更多自定义属性 ) ); // 将当前Feature加入FeatureCollection的features数组 array_push($geojson['features'], $feature); } // 如果是输出给前端,记得设置JSON响应头 header('Content-type: application/json'); // 编码为JSON并输出,JSON_PRETTY_PRINT用于格式化输出方便调试 echo json_encode($geojson, JSON_PRETTY_PRINT);
简单总结下我之前踩的坑:
- 错误地把每个Feature包装成带
features键的数组元素,直接塞到顶层数组,导致JSON出现了数字索引键 - 正确逻辑是:顶层是
FeatureCollection对象,它的features字段是一个数组,数组里的每个元素都是完整的Feature对象(包含type、geometry、properties)
内容来源于stack exchange

