【问题标题】:ST_asGeoJson for Multilinestring in php for leafletST_asGeoJson for Multilinestring in php for Leaflet
【发布时间】:2017-10-07 06:28:31
【问题描述】:

我有一个 php 代码,它运行一个查询以将数据库中的 Multilinestring geom 字段转换为 geojson 数据。此代码适用于多面体和点几何数据,但在解析多线字符串几何字段时会出现一些错误。

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

我猜这个错误主要是因为几何值之前的双引号。不知道怎么解决。

有没有其他方法可以将多线串geom数据作为geojson获取?

【问题讨论】:

    标签: php json leaflet geojson multilinestring


    【解决方案1】:

    你的问题是

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

    返回的是一个字符串,而不是一个字典(或者是一个“有序映射”,或者 PHP 用语中的“数组”)。字符串是 PostgreSQL 可以将 JSON 传递给 PHP 代码的唯一方式。

    通过执行以下操作,您将获得更好的结果:

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

    【讨论】:

      【解决方案2】:

      错误是多余的引号。

      通过替换行将其删除

      echo (json_encode($collection,JSON_NUMERIC_CHECK));
      

      以下

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

      【讨论】:

        猜你喜欢
        • 2011-10-31
        • 1970-01-01
        • 2010-09-19
        • 2018-11-14
        • 2020-08-22
        • 1970-01-01
        • 2011-07-12
        • 2021-11-19
        相关资源
        最近更新 更多