title: php: finding latitude and longitude boundaries based on a central lat/lng and distance
body: <p>I was working with the solution to a very <a href="https://stackoverflow.com/questions/8135243/finding-towns-within-a-10-mile-radius-of-postcode-google-maps-api">similar question</a> and upon implementation I discovered that it was producing a tall rectangle with the returned coordinates instead of a square (please see Matthias' answer to the other question).</p>
  <p>I only needed an array to be returned as this is to work with WordPress which has it's own preferred query method.</p>
  <p>Here's my implementation:</p>
  <pre><code>function bar_get_nearby( $lat, $lng, $limit = 50, $distance = 50, $unit = 'mi' ) {
      
      // radius of earth; @note: the earth is not perfectly spherical, but this is considered the 'mean radius'
      if( $unit == 'km' ) { $radius = 6371.009; }
      elseif ( $unit == 'mi' ) { $radius = 3958.761; }
  
      // latitude boundaries
      $maxLat = ( float ) $lat + rad2deg( $distance / $radius );
      $minLat = ( float ) $lat - rad2deg( $distance / $radius );
  
      // longitude boundaries (longitude gets smaller when latitude increases)
      $maxLng = ( float ) $lng + rad2deg( $distance / $radius / cos( deg2rad( ( float ) $lat ) ) );
      $minLng = ( float ) $lng - rad2deg( $distance / $radius / cos( deg2rad( ( float ) $lat ) ) );
  
      $max_min_values = array(
          'max_latitude' =&gt; $maxLat,
          'min_latitude' =&gt; $minLat,
          'max_longitude' =&gt; $maxLng,
          'min_longitude' =&gt; $minLng
      );
      
      return $max_min_values;
      
  }
  </code></pre>
  <p>If I give I geocode (via Google Maps API) my desired postcode of G2 1QX and a distance of 5 miles I get a lat/lng of -4.2556347/55.8620472 with the function returning this array:</p>
  <pre><code>Array
  (
      [max_latitude] =&gt; -4.18326890233
      [min_latitude] =&gt; -4.32800049767
      [max_longitude] =&gt; 55.9346130696
      [min_longitude] =&gt; 55.7894813304
  )
  </code></pre>
  <p>Any ideas? Many thanks in advance.</p>
  <p>Cheers,
  RS</p>