2017-05-09 72 views
0

我有一個php代碼,它運行查詢將Multilinestring geom字段從數據庫轉換爲geojson數據。此代碼適用於multipolygon和點geom數據,但在解析多線串geom字段時會出現一些錯誤。ST_asGeoJson for Multilinestring in php for leaflet

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

     } 

我得到上運行的代碼的響應

{"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"} 
    } 
    ] 
} 

如果我嘗試刪除\斜線使用功能的stripslashes

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

我仍然得到錯誤

SyntaxError: Unexpected token t in JSON at position 72 

我猜錯誤主要是因爲幾何體的值之前的雙引號。不知道如何解決它。

是否有任何其他方式獲得多線串geo數據geojson?

回答

1

您的問題,更換線路

echo (json_encode($collection,JSON_NUMERIC_CHECK)); 

刪除它是

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

是返回,而不是一個字典(或一個「有序地圖」或PHP中的「數組」)。字符串是PostgreSQL可以將JSON傳遞給您的PHP代碼的唯一方式。

你將不得不做這樣的事情更好的結果:

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

錯誤是多餘的引號。

通過以下

$trial=stripslashes(json_encode($collection,JSON_NUMERIC_CHECK)); 
      $trial= str_replace('"{"type"','{"type"',$trial); 
      $trial= str_replace('}","properties"','},"properties"',$trial); 
echo $trial;