Jump to content

Geo Search using Haversine formula, distinct not working


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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.