[英]Laravel Parse `geometry` data type from `MYSQL` database to the original coordinates
I have a geometry
(geometry is the data type and column name) column in the MYSQL table called geofences
, and I need to parse or convert this geometry
value to a readable array of coordinates.我在 MYSQL 表中有一个名为geofences
的geometry
(几何是数据类型和列名)列,我需要将此geometry
值解析或转换为可读的坐标数组。 So I have an approach already done what I want but I believe there is a better way out there to do it here's my approach.所以我有一种方法已经完成了我想要的,但我相信有更好的方法来做到这一点,这是我的方法。
here's how I select my geometry value from my database这就是我 select 我的数据库中的几何值的方法
DB::raw("(ST_AsText(geometry)) AS `geometry`")
The QUERY output查询 output
"POLYGON((46.646748 24.562727,46.645079 24.561795,46.643556 24.563615,46.64539 24.564747,46.646748 24.562727,46.646748 24.562727))"
I added an accessor in the Geofence
model.我在地理围栏Geofence
中添加了一个访问器。
public function getGeometryAttribute($value): array
{
$slice = Str::between($value, '((', '))');
if ($this->shape_type == 'circle') {
$slice = Str::between($value, '(', ')');
}
return collect(explode(',', $slice))->map(function ($point) {
$points = explode(' ', $point);
return [
'longitude' => $points[0],
'latitude' => $points[1],
];
})->toArray();
}
The output as I expect output 正如我所料
array:6 [
0 => array:2 [
"longitude" => "46.646748"
"latitude" => "24.562727"
]
1 => array:2 [
"longitude" => "46.645079"
"latitude" => "24.561795"
]
2 => array:2 [
"longitude" => "46.643556"
"latitude" => "24.563615"
]
3 => array:2 [
"longitude" => "46.64539"
"latitude" => "24.564747"
]
4 => array:2 [
"longitude" => "46.646748"
"latitude" => "24.562727"
]
5 => array:2 [
"longitude" => "46.646748"
"latitude" => "24.562727"
]
]
If someone knows a better way to handle this case kindly advise me here.如果有人知道处理这种情况的更好方法,请在这里给我建议。 Thanks in advance.提前致谢。
Judge Jules found the issue in comments.朱尔斯法官在评论中发现了这个问题。
DB::raw("(ST_AsText(geometry)) AS `geometry`")
Should be:应该:
DB::raw("(ST_AsGeoJSON(geometry)) AS `geometry`")
The output is now: output 现在是:
{
"type":"Polygon",
"coordinates":
[
[
[46.646748,24.562727],
[46.645079,24.561795],
[46.643556,24.563615],
[46.64539,24.564747],
[46.646748,24.562727],
[46.646748,24.562727]
]
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.