-2
$lat = isset($request->lat) ? $request->lat : '';
$lng = isset($request->lng) ? $request->lng : '';


$query = Vehicle::query();
$query->whereHas('vendor', function($q) use($lat, $lng){
   $q->where('vendor_status', 1);
   if((isset($lat) && $lat !== '') && (isset($lng) && $lng !== '')){
     //vendor table have two column like vendor_lat and vendor_lng
   }
 });

i want to find vendor nearest 50km from lat long.

divakar
  • 61
  • 2
  • 10
  • https://dev.mysql.com/doc/refman/5.7/en/spatial-analysis-functions.html – Shobi Mar 03 '20 at 11:11
  • https://en.wikipedia.org/wiki/Haversine_formula – Shobi Mar 03 '20 at 11:11
  • _Small Point_ That code will quite happily set `$lat` and `$lng` to nothing and then continue on to the rest of the code – RiggsFolly Mar 03 '20 at 11:13
  • You can check this https://developers.google.com/maps/solutions/store-locator/clothing-store-locator#finding-locations-with-mysql – Ata Mar 03 '20 at 12:07

1 Answers1

3

consider two lat long 18.5789 & 73.7707 respectively , longitude  & Longitude columns in vechiles table as defined below , radius of 50 kms

SELECT id, ( 6371 * acos( cos( radians(18.5789) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(73.7707) ) + sin( radians(18.5789) ) * sin( radians( latitude ) ) ) ) AS distance FROM vechiles HAVING distance < 50 ORDER BY distance ;

note 6371 is radius of earth in Km , use 3,963 to get distance in miles .

Above Code can be written as

 Vehicle::select(DB::raw("id, ( 3959 * acos( cos( radians('$latitude') ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians('$longitude') ) + sin( radians('$latitude') ) * sin( radians( latitude ) ) ) ) AS distance"))->havingRaw('distance < 50')->orderBy('distance')
        ->get();         
Kunal Rajput
  • 664
  • 1
  • 7
  • 21