Phil Kearney
Phil Kearney

Reputation: 157

Calculate distance between 2 set of lon and lat

As my question states that's I am looking for a function/formula that can calculate a distance between two points. Now I have looked at example and found great functions but none of them seem to work they all return 0 when I supply 2 sets of points. Basically I will need to pass the function the following (lat1,lon1,lat2,lon2) and get back the distance. From this distance I can check a check if another point is close by.

UPDATE Okay so I am now using the following function,

BEGIN
    DECLARE pi, q1, q2, q3 , roundedVal  FLOAT ;
      DECLARE rads FLOAT DEFAULT 0;
      SET pi = PI();
      SET lat1 = lat1 * pi / 180;
      SET lon1 = lon1 * pi / 180;
      SET lat2 = lat2 * pi / 180;
      SET lon2 = lon2 * pi / 180;
      SET q1 = COS(lon1-lon2);
      SET q2 = COS(lat1-lat2);
      SET q3 = COS(lat1+lat2);
      SET rads = ACOS( 0.5*((1.0+q1)*q2 - (1.0-q1)*q3) ); 
      RETURN FORMAT((6371 * rads) , 1);
    END

This works fine with Kilometres, but what I am looking for is meters. So I know I have the change the numbers in that function but which ones and what to. Any help ?

Upvotes: 0

Views: 1829

Answers (4)

skaur
skaur

Reputation: 168

apply this on the values

double theta = src_longitude - dest_longitude;
double min_distance = (Math.sin(Math.toRadians(src_latitude)) * Math.sin(Math.toRadians(dest_latitude))) +(Math.cos(Math.toRadians(src_latitude)) * Math.cos(Math.toRadians(dest_latitude)) * Math.cos(Math.toRadians(theta)));
min_distance = Math.acos(min_distance);
min_distance = Math.toDegrees(min_distance);
min_distance = min_distance * 60 * 1.1515 * 1.609344;

Upvotes: 0

Naveen Kumar
Naveen Kumar

Reputation: 4601

Try this query

$qry = "SELECT *,(((acos(sin((".$latitude."*pi()/180)) *
sin((`Latitude`*pi()/180))+cos((".$latitude."*pi()/180)) * cos((`Latitude`*pi()/180))*
cos(((".$longitude."- `Longitude`)*pi()/180))))*180/pi())*60*1.1515) as distance FROM
'MyTable` WHERE distance >= ".$distance."

Upvotes: 0

Charlie
Charlie

Reputation: 1031

I have used this webiste in the past and it has worked for me. Has lots of useful formulas and gives examples in javascript.

http://www.movable-type.co.uk/scripts/latlong.html

Upvotes: 2

KingCronus
KingCronus

Reputation: 4519

I'd recommend you take a look at a spacial extention to MySQL.

http://dev.mysql.com/doc/refman/5.0/en/spatial-extensions.html

If you don't fancy that, this blog might have some use to you:

http://zcentric.com/2010/03/11/calculate-distance-in-mysql-with-latitude-and-longitude/

Upvotes: 1

Related Questions