简体   繁体   中英

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

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:

{
    "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]
        ]
    ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM