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. 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
DB::raw("(ST_AsText(geometry)) AS `geometry`")
The QUERY 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.
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
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.