简体   繁体   中英

how to search all the location for given distance and given latitude and longitude in laravel

This is my senario: I saved shop details in mysql database in following way.

shopName, latitude, longitude,

now if someone gives his location in latitude and longitude with a distance (like 5km) I needs to filler all the shops within 5km to him,

in here user is the center and radius is 5km and I need to find all the shop within that circle, my application is developed in laravel 5.1

I tried to follow this code , but it wouldn't work.

can anyone help me.

You can add the following code in your model

public function ScopeDistance($query,$from_latitude,$from_longitude,$distance)
{
  // This will calculate the distance in km
  // if you want in miles use 3959 instead of 6371
  $raw = \DB::raw('ROUND ( ( 6371 * acos( cos( radians('.$from_latitude.') ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians('.$from_longitude.') ) + sin( radians('.$from_latitude.') ) * sin( radians( latitude ) ) ) ) ) AS distance');
  return $query->select('*')->addSelect($raw)->orderBy( 'distance', 'ASC' )->groupBy('distance')->having('distance', '<=', $distance);
}

And you can use it with something like this

$ads = Ad::with(['user','photos'])->distance($from_latitude,$from_longitude,$distance)->get();

check this one out: Calculate distance given 2 points, latitude and longitude

for the code part of the question, i think the fastest would be to divide the computation in two.

first our build a 5x5km square from the coordinates, then you select every shop between those, with the whereBetween clause in laravel.

the you calculate the precise distance with the formula from the link. Basically its 5 =< sqrt((latitude1-latitude2)^2+(longitude1-longitude2)^2)

just "convert" (latitude1-latitude2) and (longitude1-longitude2) to kilometers :)

Fine tune the parameters.I have given .50 but you can choose a much lesser value, to reduce the coverage area.

$latitude = \Input::get('latitude');
$longitude = \Input::get('longitude');

$upper_latitude = $latitude + (.50); //Change .50 to small values
$lower_latitude = $latitude - (.50); //Change .50 to small values
$upper_longitude = $longitude + (.50); //Change .50 to small values
$lower_longitude = $longitude - (.50); //Change .50 to small values

$result = \DB::table('table')
        ->whereBetween('geo_locations.latitude', [$lower_latitude, $upper_latitude])
        ->whereBetween('geo_locations.logitude', [$lower_longitude, $upper_longitude])
        ->get();

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