Friday, October 17, 2014

How to get all addresses with in a radius from a fixed point in database?

Get all Lat. & Lng. w.r.t. a Lat. & Lng. in a radius:

If you want to find out all the latitudes and longitudes with in a given radius from a given latitude & longitude in a database then you have to do this task.

DB Structure:

id    lat                  lng
1    37.386337     -122.085823
2    37.393887     -122.078918
3    37.394012     -122.095528
4    37.402653     -122.079353


In PHP we can use this kind of variables:

$lat = 37, $lng= -122, $radius= 28;

Now if we want to use its radius should be in miles then we will use code 3959
Now if we want to use its radius should be in k.m. then we will use code 6371

Then query is :

"SELECT *,lat, lng, ( 3959 * acos( cos( radians( $lat ) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians( $lng ) ) + sin( radians( $lat ) ) * sin( radians( lat ) ) ) ) AS distance FROM table  HAVING distance < $radius ORDER BY distance "

You will get a result all the latitudes and longitude ids which are exists with in 28 miles radius from your given latitude and longitude.

Thanks
 

No comments:

Post a Comment