Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distance by zip code formula

I found this formula and it works, however what i trying to do is to give ability to filter by distance from his ZIP code.

I found formula that calculates distance between two latitude and longitude coordinates.

(3956 * ACOS(COS(RADIANS(start_lat)) * COS(RADIANS(end_lat)) * COS(RADIANS(end_lon) - RADIANS(start_lon)) + SIN(RADIANS(start_lat)) * SIN(RADIANS(end_lat))))

I have filter on page that sends following info

$_POST["start_latitude"] = 34.023179;
$_POST["start_longitude"] = -118.303965;
$_POST["max_distance"] = 50;

If i do

SELECT (3956 * ACOS(COS(RADIANS({$_POST["start_latitude"]})) * COS(RADIANS(34.018626)) 
        * COS(RADIANS(-118.249978) - RADIANS({$_POST["start_longitude"]}))
         + SIN(RADIANS({$_POST["start_latitude"]})) * SIN(RADIANS(34.018626))))

Will output distance as number of miles 4 miles in this case.

How can i convert this formula for my goal to find places no longer than say 50 miles from coordinates entered? I know all need to be done is change of places in formula, but i am not good with school math.

SELECT place_name FROM places 
    WHERE place_latitude = ? AND place_longitude = ?

EDIT:

I have places table where i got 1000 records in format

id place_name latitude longitude
 1  xxx        432423   -43432
 2  yyy        523452   -54353
 3  zzz        553453   -53422
etc.

So the formula has to do something like

SELECT place_name FROM places 
   (CALCULATE each place distance from 
    $_POST["start_latitude"] and $_POST["start_longitude"]
    and select only ones that) < 50
like image 530
Roman Toasov Avatar asked Jul 05 '26 22:07

Roman Toasov


1 Answers

Put the distance formula into the WHERE clause:

SELECT place_name
FROM places
WHERE (3956 * ACOS(COS(RADIANS(:start_latitude)) * COS(RADIANS(latitude)) * COS(RADIANS(-longitude) - RADIANS(:start_longitude)) + SIN(RADIANS(:start_latitude)) * SIN(RADIANS(latitude))))
    < :max_distance
like image 119
Barmar Avatar answered Jul 07 '26 13:07

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!