Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get all points within a given range based on its latitude and longitude?

scenario: I have a db with three tables, users, locations, stock;

within users I have: id, name, email

within locations I have: id, place, lati, logi

within stock I have: id, user_id, product, total_count, location_id

I am fairly new and I managed to join all the tables:

$qry = "
SELECT COUNT(id)
  FROM stock
  LEFT
  JOIN users 
   ON stock.user_id= users.id
  LEFT
  JOIN locations
   ON stock.location_id= locations.id ";

But what I am hoping to be able to do is sort it by distance using the lati and logi. So for example, I want everything within 25 miles, sorted closest to furthest.

How can i pull this off giving the scenario?

I did some googling but everything i'm finding show me how I can get the distance between two points, but what I want to be able to use one set of points, and get everything within X miles of it?

Not sure if that all makes sense ?

like image 792
Keezy Avatar asked Nov 08 '22 22:11

Keezy


1 Answers

I have come up with below simplified formula for calculating this in my application :

pow(CentralLati - LatitudeofCircle, 2) + pow(CentralLongi - LongitudeofCircle, 2) <= 4

where,

CentralLati , CentralLongi => co-ordinates of a point A

LatitudeofCircle, LongitudeofCircle => co-ordinates of the points 25kms around the point A.

You may adjust the above formula to match your database naming conventions.

Hope I understood your requirement correctly.

like image 137
Yesh Avatar answered Nov 14 '22 21:11

Yesh