【问题标题】:Querying SQL using Php and outputting geojson for a GeoPolygon使用 PHP 查询 SQL 并为 GeoPolygon 输出 geojson
【发布时间】:2017-12-31 06:11:46
【问题描述】:

在 PHP 中为存储在 MySQL 数据库中的 Geo Polygon 输出 geojson

我尝试了很多东西,包括geoPHP插件https://geophp.net/geos.html但到目前为止没有成功,也尝试使用ST_AsGeoJSON但没有用

$sql = "select ST_AsGeoJSON(ST_GeomFromText('coordinates')) from buildings where id = 1";

https://dev.mysql.com/doc/refman/5.7/en/spatial-geojson-functions.html

我正在尝试实现与此类似的输出

"shape":{"type":"Polygon","coordinates":[[[53.294974,-6.426631],[53.294847,-6.426419],[53.294289,-6.426888],[53.294326,-6.427194],[53.294974,-6.426631]]]}

这是我的插入语句 -

INSERT INTO `mrp_buildings` (
  `buildingId`, `companyId`, `name`, `noOfFloors`,
  `coordinates`, `city`, `country`, `address`, `phone`,
  `email`) VALUES (
    '1', '1', 'My Sample Building', '4',
    PolyFromText('POLYGON((33.294974 -2.426631, 53.294847 -6.426419,
      73.294289 -6.426888, 13.294326 -6.427194, 43.294974 -6.426631,
      33.294974 -2.426631))'), 'Dublin', 'Ireland', 'Mayor Street', '089449 8500', 'email@example.ie ');

任何建议 -

【问题讨论】:

  • 对不起我的英语

标签: php mysql geospatial geojson


【解决方案1】:

获取您的数据库行,使用 JSON 键制作一个数组,然后 json_encode()

当然,你存储坐标的方式很乱,真的需要像这样把$coordinates变成一个数组:

$coordinates = [
    [
        55.123456,
        0.123456,
    ],
    [
       //etc
    ]

为了做到这一点,你需要先摆脱你不需要的东西:

$string = $row['coordinates']; /* POLYGON((33.294974 -2.426631, 53.294847 -6.426419,
      73.294289 -6.426888, 13.294326 -6.427194, 43.294974 -6.426631,
      33.294974 -2.426631)) */

$string = str_replace('POLYGON', '', $string); /* ((33.294974 -2.426631, 53.294847 -6.426419,
  73.294289 -6.426888, 13.294326 -6.427194, 43.294974 -6.426631,
  33.294974 -2.426631)) */

 $string = str_replace('(', '', $string);
 $string = str_replace(')', '', $string); // remove brackets

 $coords = explode(',' $string);

此时您将拥有一组坐标,但 X 和 Y 都是由空格分隔的一个值,因此我们也需要分解它。

$coordinates = [];
foreach ($coords as $co) {
    $ex = explode(' ', $co);
    $coordinates[] = [
        $ex[0], $ex[1];
    ];
}

最后您可以创建数组以进行 JSON 编码:

$array = []; //empty array

$array['shape'] = [
    'type' => 'Polygon',
    'coordinates' => $coordinates
];

$json = json_encode($array);

我希望这会有所帮助!如果可以,请尝试将坐标存储在 DB 中,而不需要额外的东西来为您省去所有这些麻烦!

【讨论】:

  • thanks del 但我想你不明白我的问题存储的数据是 GeoPolygon(它是一种空间数据en.wikipedia.org/wiki/Spatial_database),在 javascript 中有一些方法可以使用坐标获取此类数据。ST_ASGeoJson () 但我正在努力实现它的 php 实现
  • GeoPolygon 是数据库类型?那你可以为我转储列吗?
  • 列是类型 - 几何
猜你喜欢
  • 1970-01-01
  • 2015-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-31
  • 2019-02-21
  • 2020-03-26
  • 2011-01-05
相关资源
最近更新 更多