Jump to content

Geo Search using Haversine formula, distinct not working


mo

Recommended Posts

I am using the below script which works fine to query all regions in a specified radius of my input latitude and longitude. However my database has duplicate city/state pairs due to different zip codes and the query returns duplicate cities. I tried to use distinct but since the query has to be ordered by distance, I could not get this to work. Any suggestions.

 

Note: Table contains columns city, region(state), country, zip, latitude and longitude.

 

SELECT `city`, `region`, 3956 * 2 * ASIN(SQRT(POWER(SIN((
37.4404 - abs(`latitude`)) * pi()/180 / 2),2) + COS(37.4404 * pi()/180 ) * COS(abs(`latitude`) *
pi()/180) * POWER(SIN((-121.8705 - `longitude`) * pi()/180 / 2), 2) )) as distance
FROM `locationdb`
having distance < 20
ORDER BY distance limit 10

Here are my current results. I have logic in my PHP to loop through the result and remove duplicates but that is a sloppy way of removing the duplicates and since the cities are not in order, the logic does not always work.

 

city region distance Ascending

--------------------------------------------

Milpitas CA 0

San Jose CA 4.05605867292861

San Jose CA 4.27379165682789

San Jose CA 4.72803292240825

San Jose CA 5.10657017304142

Fremont CA 5.37310902047679

Santa Clara CA 5.86235168930009

San Jose CA 6.31906928616225

Alviso CA 6.57871062331007

Fremont CA 6.7615683089475

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.