4

Does django have anything that will look at a geographic coordinate (decimal lat/long) and determine if is inside a circle with a certain radius (let's say 100 Km)?

I have certain type of data, each has a lat/long and I would like to make a search in the database to see if that data is located inside of a circle with a specified radius size.

I could probably write something myself that will handle this but I wander if there is something written already that will handle this.

avatar
  • 12,087
  • 17
  • 66
  • 82

1 Answers1

12

This problem can be solved in pure SQL if you dont mind about very good precision.

You can find points around a GPS position with this specific SQL query :

# find point around :
latitude = 46.2037010192871
longitude = 5.20353984832764
query= "SELECT ID, NOM, LAT, LON, 3956 * 2 * ASIN(SQRT(POWER(SIN((%s - LAT) * 0.0174532925 / 2), 2) + COS(%s * 0.0174532925) * COS(LAT * 0.0174532925) * POWER(SIN((%s - LON) * 0.0174532925 / 2), 2) )) as distance from POI  having distance < 50 ORDER BY distance ASC " % ( latitude, latitude, longitude)

This will give you all records with gps records in a 50km area.

You can easily plug this in django with :

from django.db import connection
cursor = connection.cursor()
cursor.execute( query )
rows = cursor.fetchall()

or with django raw queries

jujule
  • 11,125
  • 3
  • 42
  • 63
  • Thank you jujule. I think this will work. I don't want to mess yet with the geodjango. This is just perfect. – avatar Jan 06 '11 at 01:03
  • I just looked up some postgis documentation out of curiosity and found this. http://postgis.refractions.net/documentation/manual-1.5/ST_DWithin.html It just seems a bit more simple if you are using postgis already. – Benbob Jan 06 '11 at 01:16
  • Thank you Keyo. I think I should switch to Postgres from MySQL since Postgres seems to have more support for GIS stuff. – avatar Jan 06 '11 at 01:33
  • I don't know much about it other than GIS professions seem to hate MySQL. Since you're on Django it shouldn't take much effort to switch database. – Benbob Jan 06 '11 at 03:02