title: Find subsidiary by latitude and longitude (geolocation)
body: <p>I'm looking for a <strong>fast MySQL query</strong> that returns the <strong>nearest location</strong> from a simple table:</p>
  
  <p>Table: <code>locations</code>:</p>
  
  <pre><code>id |    city    |   latitude   |  longitude
  -----------------------------------------------
  1  |   Berlin   |   52.524268  |   13.406290
  -----------------------------------------------
  2  |   London   |   51.508129  |  -0.1280050    
  -----------------------------------------------
  3  |   Hamburg  |   53.551084  |   9.9936817
  -----------------------------------------------
  </code></pre>
  
  <p>Client's coordinates (<a href="/questions/tagged/latitude" class="post-tag" title="show questions tagged 'latitude'" rel="tag">latitude</a> + <a href="/questions/tagged/longitude" class="post-tag" title="show questions tagged 'longitude'" rel="tag">longitude</a>):</p>
  
  <pre><code>$intLat = '52.370215700000000000'; // lat Amsterdam
  $intLon = '4.895167899999933000';  // lon Amsterdam
  </code></pre>
  
  <p>Most provided examples @<a href="http://stackoverflow.com">SO</a> are based on a <em>distance calculation</em>.</p>
  
  <p>Even with coordinates from <a href="http://www.distancesfrom.com/gb/Birmingham-latitude-longitude-Birmingham-latitude-Birmingham-longitude/LatLongHistory/12985.aspx" rel="nofollow"><strong>Birmingham</strong></a>, it returns <code>id=1</code> (Berlin).
  The query should return London, because it is closer than Berlin. Shouldn't?</p>
  
  <pre><code>SELECT *, ( 3959 * acos( cos( radians($intLat) ) 
                    * cos( radians( latitude ) ) 
                    * cos( radians( longitude ) 
                    - radians($intLon) ) + sin(radians($intLat) ) 
                    * sin( radians( latitude ) ) ) ) AS distance 
  FROM locations 
  HAVING distance &lt; 10 
     AND id IN(1,2,3) 
  LIMIT 1;
  </code></pre>