Thursday, June 16, 2011

Calculate the distance using lattitude, longitude and ZIP codes in MySQL

So, assuming we have a table:

ZIP_CODES
zip_code | lattitude | longitude

We take this zip code from NY
$zip = 10001
$lat = 40.750742
$lon =-74.52976

What we need is the Earth radius (6371 km).

If we need to search the zip codes that are in a 10 km area, we could use this 'small' sintax:


2 * 6371 * ATAN2( (SIN( ( ($lat - lattidude) * PI() / 180 ) / 2 ) * SIN( ( ($lat - lattidude) * PI() / 180 ) / 2 ) + SIN( ( ($lon - longitude) * PI() / 180 ) / 2 ) * SIN( ( ($lon - longitude) * PI() / 180 ) / 2 ) * COS(lattitude) * COS($lat)) , ( 1 - (SIN( ( ($lat - lattidude) * PI() / 180 ) / 2 ) * SIN( ( ($lat - lattidude) * PI() / 180 ) / 2 ) + SIN( ( ($lon - longitude) * PI() / 180 ) / 2 ) * SIN( ( ($lon - longitude) * PI() / 180 ) / 2 ) * COS(lattitude) * COS($lat)) ) ) < 10

For this calculation, i used the harvesine formula to calculate the great-circle distance between two points (the shortest distance over the earth's surface - ignoring any hills).

This formula remains particularly well-conditioned for numerical computation even at small distances – unlike calculations based on the spherical law of cosines.

Hope this helps.

No comments:

Post a Comment