0

我正在尝试使用 MySQL 空间数据类型尽可能本地处理地图标记位置。我不想求助于额外的列,lat最终lng,,我也希望能够对线和多边形(以及其他几何图形)进行编码。该表具有point列类型:

Schema::create('maps', function (Blueprint $table) {
    $table->increments('id');
    $table->point('map_center')->nullable();
    $table->timestamps();
});

在视图方面,考虑到在数据库中创建这些空间类型的内置支持,Eloquent 比我想象的要笨一些。如果我get()是模型,map_center则显示原始编码几何。

>>> $map=Map::first()
=> App\Map {#2935
     id: 1,
     map_center: b"\0\0\0\0\x01\x01\0\0\0ºõš\x1E\x14\x7FRÀb0\x7F…Ì_D@",
     created_at: null,
     updated_at: null,
   }

我写了一个center()方法,它返回一个包含 lat 和 long 的对象:

public function center()
{
    if ($this->map_center) 
    {
        $result = DB::select('
            select ST_Y(map_center) as lat, ST_X(map_center) as lng 
            from maps 
            where id = :id
        ', 
        ['id' => $this->id]);
        $center['lat'] = $result[0]->lat;
        $center['lng'] = $result[0]->lng;
        return (object) $center;
    }
    else
    {
        dd($this);
    }
} 

输出:

>>> $map->center()->lat
=> 40.748429

这是一个不错的解决方法,但有点难看。相反,我希望 Eloquent 提取它,以便模型返回人类可读的坐标,例如:

>>> $map=Map::first()
=> App\Map {#2935
     id: 1,
     map_center: {
       lat: 40.748429,   // or X: and Y:
       lng: -73.985603, 
     }
     created_at: null,
     updated_at: null,
   }

鉴于它是一种point类型(具有两个组件),是否可以使用ST_AsText(p)包含ST_X(p)and的对象自动检索数据ST_Y(p)

这可能吗?

4

1 回答 1

1

MySQL 将数据存储为 WKB(众所周知的二进制)格式。

看看这里PHP 中 MySQL 二进制 GEOMETRY 字段的转换

您可以使用模型属性。它应该是这样的。

public function getMapCenterAttribute()
{
    $center = unpack('Lpadding/corder/Lgtype/dlatitude/dlongitude', $this->map_center);
    return $center;
}

如果需要,您还应该使用类似的功能setMapCenterAttribute反向执行此操作pack

于 2019-01-23T17:37:18.720 回答