0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

laravel ライブラリを使っての位置情報検索

Last updated at Posted at 2022-03-15

上記ライブラリ無しバージョンを参考に、ライブラリありをやってみる。

composer require grimzy/laravel-mysql-spatial
Geo.php

use Grimzy\LaravelMysqlSpatial\Eloquent\SpatialTrait;

class Geo extends Model
{
    use SpatialTrait;

    protected $spatialFields = [
        'location',
    ];
}

実践

HogesController.php
    public static function test(request $request)
    {

//        名古屋駅
//        $lng = 136.881537;//経度 縦方向
//        $lat = 35.170915;//緯度 横方向

//        青森
        $lng = 140.850702;
        $lat = 40.881797;

        $res = Geo::query()
            ->orderByRaw('ABS(Y(location) - ? ) + ABS(X(location) - ? )', [$lng, $lat])
            ->get();

        foreach ($res as $v) {
            echo $v->name . "<br>";
        }
    }

近い順に並びましたね!

注意

モデル に spatialFields を適切に指定しないとエラーになる

at /var/www/html/twikon.club/vendor/laravel/framework/src/Illuminate/Http/JsonResponse.php:88
 possibly incorrectly encoded {"exception":"[object] (InvalidArgumentException(code: 0): Malformed UTF-8 characters,
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?