Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you don't need to be very exact in your range, you can use an approximation to calculate the latitude and longitude ranges. Concept explained <a href="http://www.johndcook.com/blog/2009/04/27/converting-miles-to-degrees-longitude-or-latitude/" rel="noreferrer">here</a>:</p> <p>Using the city location and distance, find the change in latitude (this remains the same no matter where), and approximate change in longitude (varies based on latitude). Then calculate a bounding box.</p> <pre><code>import math # earth_radius = 3960.0 # for miles earth_radius = 6371.0 # for kms degrees_to_radians = math.pi/180.0 radians_to_degrees = 180.0/math.pi def change_in_latitude(distance): "Given a distance north, return the change in latitude." return (distance/earth_radius)*radians_to_degrees def change_in_longitude(latitude, distance): "Given a latitude and a distance west, return the change in longitude." # Find the radius of a circle around the earth at given latitude. r = earth_radius*math.cos(latitude*degrees_to_radians) return (distance/r)*radians_to_degrees def bounding_box(latitude, longitude, distance): lat_change = change_in_latitude(distance) lat_max = latitude + lat_change lat_min = latitude - lat_change lon_change = change_in_longitude(latitude, distance) lon_max = longitude + lon_change lon_min = longitude - lon_change return (lon_max, lon_min, lat_max, lat_min) </code></pre> <p>To calculate events within distance <code>kms</code> of <code>city</code>:</p> <pre><code>lon_max, lon_min, lat_max, lat_min = bounding_box(city.lat, city.lon, kms) events = Event.objects.filter( city__lat__lte=lat_max, city__lat__gte=lat_min, city__lon__lte=lon_max, city__lon__gte=lon_min ) </code></pre> <p>Keep in mind that the error becomes larger with large distances, and the closer your are to the poles. There is also an issue with places near the anti-meridian (international date line), but that's easy to check for (check if longitude is > 180 or &lt; -180).</p> <p>If you want more acurate results, you can use this method as a first pass and then use your function, so you don't have to go through every event individually.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload