Ninja
Ninja

Reputation: 438

Get latitude and longitude at 50 miles radius with reference to particular latitude and longitude

I have latitude and longitude value and want to find another lat long value at 50 miles of it. How to do that? Any formula or custom function to get that in php?

Upvotes: 2

Views: 2320

Answers (2)

Valerie Bantilan
Valerie Bantilan

Reputation: 121

This query method is base on the google map store locator api.

Please refer this website:

Let say you have a variable of lat and lang $lat; $lng;

Let us assume that those variable has its coordinates.

In your query do this:

SELECT id, lat, lng ( 3959 * acos( cos( radians($lat) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians($lng) ) + sin( radians($lat) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance <= 50 ORDER BY distance;

The result will return the id, lat, and lng coordinates that is less than or equal to 50 miles.

P.S The 3959 is the unit to return the miles.

Upvotes: 1

sathish R
sathish R

Reputation: 422

In php you could do it by fetching the records and using the below formula. But I would like you to use query to solve this problem. It's more efficient.

function getNearestUsers($givenLat,$givenLng)
{
   $res = [];
   $recs = getAllTheRecordsFromDb();
   foreach($recs as $r)
   {
      $distance = sqrt(POW((69.1 * ($r['lat'] - $givenLat)),2) + POW((69.1 * ($givenLng - $r['lng']) * cos($r['lat'] / 57.3)),2));
      if($distance<=50)  //50 miles
       {
          //some code
       }
   }
}

Suppose you have user table which has userId, latitude and longitude. Below is sql query to get users who are in radius of 50 miles from the given latitude and longitude.

SELECT userId, latitude, longitude, SQRT(
    POW(69.1 * (latitude - [givenLat]), 2) +
    POW(69.1 * ([givenLng] - longitude) * COS(latitude / 57.3), 2)) AS distance
FROM TableName HAVING distance < 50 ORDER BY distance;

You could get more answer from referring the below link: latitude/longitude find nearest latitude/longitude - complex sql or complex calculation

Upvotes: 1

Related Questions