GeoJSON is a text format for encoding various geographical structures. I have a large number of point data with various extra information stored in a postgresql data base. I fetch all the data into an array in php, using PDO::FETCH_ASSOC, that is each row that has been fetched is an item in a numerical array, for each row, the various fields are coded as an associative array, so I have a structure like
Array
(
[0] => Array
(
[id] => 210
[name] => Sellafield
[lat] => 54.43
[lon] => -3.52
[type] => Reprocessing plant
[country] => Great Britain
)
[1] => Array
(
[id] => 177
[name] => Dounreay
[lat] => 58.57
[lon] => -3.73
[type] => Reprocessing plant
[country] => Great Britain
)
)
Now I want to use the lat and lon field to create the coordinate fields in GeoJSON and store the rest of the information as properties. Having the dataset stored as $dataset, I run the following code
$minlat=100;
$maxlat=-100;
$minlon=400;
$maxlon=-200;
foreach($dataset as &$item){ # Uses a pointer to refer to $item, so that changes are reflected in $dataset
$item['geometry']['type']='Point';
# Must make sure the coordinates are stored as numbers, not strings
$lon=$item['lon']*1;
$lat=$item['lat']*1;
$item['geometry']['coordinates']=array($lon,$lat);
$minlon=min($minlon,$lon);
$maxlon=max($maxlon,$lon);
$minlat=min($minlat,$lat);
$maxlat=max($maxlat,$lat);
unset($item['lat']);
unset($item['lon']);
foreach($item as $k=>$v){
# Don't want to mess with geometry as it is already set
# Id should also be set directly.
if(!($k='geometry' || $k=='id')) {
# Must make sure that numeric values are correctly handled
if(is_numeric($v)?$v*1:$v;
$props[$k]=$v;
unset($item[$k]);
}
}
$item['type']='Feature';
$item['properties']=$props;
}
$dataset=array("type"=>"FeatureCollection","features"=>$dataset);
$dataset['bbox']=array($minlon,$minlat,$maxlon,$maxlat);
# Defining crs for WGS84 lat/lon
$dataset['crs']=array("type"=>"name","properties"=>array("name","urn:ogc:def:crs:EPSG::4326"));
$json=json_encode($dataset);