Create GeoJSON in php

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

    [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

foreach($dataset as &$item){ # Uses a pointer to refer to $item, so that changes are reflected in $dataset
   # Must make sure the coordinates are stored as numbers, not strings      
   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
  # Defining crs for WGS84 lat/lon
This entry was posted in Diverse. Bookmark the permalink.