有没有办法在laravel中找到半径为半径的位置

问题描述 投票:2回答:2

我如何基于一个点的经纬度和给定的半径找到基于半径的位置。假设我给定的半径为30,则它将找到该特定给定纬度和经度(半径为30)的结果。我试过下面的代码:

    $lat = '37.421998'; // latitude of centre of bounding circle in degrees
    $lon = '-122.084000'; // longitude of centre of bounding circle in degrees
    $rad = 30; // radius of bounding circle in kilometers

    $R = 6371;  // earth's mean radius, km

    // first-cut bounding box (in degrees)
    $maxLat = $lat + rad2deg($rad/$R);
    $minLat = $lat - rad2deg($rad/$R);
    $maxLon = $lon + rad2deg(asin($rad/$R) / cos(deg2rad($lat)));
    $minLon = $lon - rad2deg(asin($rad/$R) / cos(deg2rad($lat)));

   $results = DB::select('Select id, latitude, longitude, acos(sin(:lat)*sin(radians(latitude)) + cos(:lat)*cos(radians(latitude))*cos(radians(longitude)-(:lon))) * (:R) As D From ( Select id, latitude, longitude From jobs_master Where latitude Between (:minLat) And (:maxLat) And longitude Between (:minLon) And (:maxLon) ) As FirstCut Where acos(sin(:lat)*sin(radians(latitude)) + cos(:lat)*cos( radians(latitude))*cos(radians(longitude)-(:lon))) * :R < :rad ', ['maxLat' => $maxLat,'maxLon' => $maxLon, 'minLat' => $minLat,'minLon' => $minLon, 'lat' => $lat,'lon' => $lon,'R'=> $R,'rad'=>$rad]);

        dd(DB::getQueryLog());exit;
        print_r($results);exit;

任何人都可以帮助我。

php laravel-5 geolocation
2个回答
1
投票

您可以使用以下计算并根据需要修改查询:

$query = "SELECT (3956 * 2 * ASIN(SQRT( POWER(SIN(( $latitude - latitude) *  pi()/180 / 2), 2) + COS( $latitude * pi()/180) * COS(latitude * pi()/180) * POWER(SIN(( $longitude - longitude) * pi()/180 / 2), 2) ))) as distance, latitude, longitude" FROM TABLES HAVING distance <= 30

因此,在上面的查询中,我们首先根据给定的纬度和经度来计算距离,然后使用HAVING子句将距离限制为30 km半径。

希望这可以解决您的问题:)


0
投票

这是使用口才查询解决Laravel问题的好方法,该方法是针对不同的情况编写的,但正是您要查找的内容:

private function findNearestRestaurants($latitude, $longitude, $radius = 400)
    {
        /*
         * using eloquent approach, make sure to replace the "Restaurant" with your actual model name
         * replace 6371000 with 6371 for kilometer and 3956 for miles
         */
        $restaurants = Restaurant::selectRaw("id, name, address, latitude, longitude, rating, zone ,
                         ( 6371000 * acos( cos( radians(?) ) *
                           cos( radians( latitude ) )
                           * cos( radians( longitude ) - radians(?)
                           ) + sin( radians(?) ) *
                           sin( radians( latitude ) ) )
                         ) AS distance", [$latitude, $longitude, $latitude])
            ->where('active', '=', 1)
            ->having("distance", "<", $radius)
            ->orderBy("distance",'asc')
            ->offset(0)
            ->limit(20)
            ->get();

        return $restaurants;
    }

参考:https://www.techalyst.com/posts/laravel-find-nearest-restaurants-from-certain-gps-latitude-and-longitude

© www.soinside.com 2019 - 2024. All rights reserved.