title: Querying for things near a geolocation?
body: <p>I have a query that attempts to find things within a certain geolocation, but the results that it brings back are a little bit... strange.</p>
  
  <p>I had previously posted this thread and the community helped me find a formula that I needed: <a href="https://stackoverflow.com/questions/4687312/querying-within-longitude-and-latitude-in-mysql/4690450#4690450">Querying within longitude and latitude in MySQL</a> but the query now gives really wacky results.  </p>
  
  <p>My data is surrounding the city of San Francisco which has the lat/lng <code>37.780182 , -122.517349</code></p>
  
  <p><strong>Query:</strong></p>
  
  <pre><code>SELECT
      id,
      hike_title,
      lat,
      lng,
      ( 3959 * acos(  cos( radians(37) )
                    * cos( radians( lat ) )
                    * cos( radians( lng ) - radians(37.780182) )
                    + sin( radians(-122.517349) ) * sin( radians( lat ) )
                   )
      ) AS distance
  FROM
      my_awesome_table
  HAVING
      distance &lt; 10000
  ORDER BY
      distance
  LIMIT
      0 , 50
  </code></pre>
  
  <p>So as you see - even if I make radius 10000 it still doesn't find much, so I wonder if my query is off.  Some of the results it brings back even have 0,0 for lat/lng which is my way to denote that there are no lat/lng for that record.</p>
  
  <p>Here is how the formula is supposed to look like:</p>
  
  <pre><code>SELECT
      id,
      ( 3959 * acos(  cos( radians(37) ) 
                    * cos( radians( lat ) )
                    * cos( radians( lng ) - radians(-122) )
                    + sin( radians(37) ) * sin( radians( lat ) )
                   )
      ) AS distance
  FROM
      markers
  HAVING
      distance &lt; 25
  ORDER BY
      distance
  LIMIT
      0 , 20;
  </code></pre>
  
  <p>Thank you and sorry for the painfully long question ! By the way, I am using MySQL.</p>
  
  <hr>
  
  <p>Hmmm,</p>
  
  <p>I just tried with the exact query you gave and it worked with 50% accuracy.  Here is a sample of the data set:</p>
  
  <pre><code>    lat          lng    
  | 37.223465 | -122.090363 |
  | 39.320980 | -111.093735 |
  | 38.031715 |  -84.495132 |
  | 37.787144 | -122.493263 |
  | 52.975361 |   -1.458620 |
  | 40.848557 | -111.906883 |
  | 40.572498 | -111.859718 |
  </code></pre>
  
  <p>So now the query returned all the items that were many miles away, but not the items which were under 100 miles away.  Like this item ( 37.787144 , -122.493263 ) was never getting returned even though it is just about 50 miles from the originating point.  Would you happen to know why?</p>