Search code examples
phpjsonleafletgeojsonmultilinestring

ST_asGeoJson for Multilinestring in php for leaflet


I have a php code which runs a query to convert the Multilinestring geom field from the database to geojson data. This code works fine for multipolygon and point geom data but there is some error while parsing a multilinestring geom field.

   <?php
include('../config.php'); // the db config file
function createFeature () {
    $feature = new stdClass();
    $feature->type = 'Feature';
    $feature->geometry = new stdClass();
    $feature->geometry->type = 'Multilinestring';
    $feature->properties = new stdClass();
    return $feature;
}

function createCollection () {
    $collection = new stdClass();
    $collection->type = 'FeatureCollection';
    $collection->features = array();
    return $collection;
}


$query = 'SELECT ST_AsGeoJson(geom) as geom,name FROM table_name';
if($result = pg_query($query)) {
          $collection = createCollection();
           while($row = pg_fetch_row($result))
            {
          $feature = createFeature();
         $feature->geometry = $row[0];
         $feature->properties->name=$row[1];
         $collection->features[] = $feature;
          }

            echo (json_encode($collection,JSON_NUMERIC_CHECK));

        }

The response I get on running the code is

 {"type":"FeatureCollection",
  "features":
  [
   { 
    "type":"Feature",
    "geometry":
     "{\"type\":\"MultiLineString\",
       \"coordinates\":[[[73.9750168196755,15.2410462374959],
                      [73.974612433675,15.2415698937723],
                      [73.9733813019535,15.2431183375569],
                      [73.9727337832775,15.2439091075613]]]
      }",
    "properties":{"name":"NH - 17"}
    }
  ]
}

If I try to remove the \ slashes using the function stripslashes

echo stripslashes(json_encode($collection,JSON_NUMERIC_CHECK));

I still get the error

SyntaxError: Unexpected token t in JSON at position 72

I guess the error is mainly because of the double quotes before the values of geometry. Don't know how to resolve it.

Is there any other way to get multilinestring geom data as geojson?


Solution

  • Your problem is that

    $feature->geometry = $row[0];
    

    is returning a string and not a dictionary (or an "ordered map", or "array" in PHP parlance). Strings are the only way that PostgreSQL can communicate JSON to your PHP code.

    You will have much better results by doing something like:

    $feature->geometry = json_decode($row[0]);