avatar
avatar

Reputation: 12495

Django - determining if geographic coordinates are inside of an circle

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.

Upvotes: 4

Views: 2672

Answers (1)

jujule
jujule

Reputation: 11531

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

Upvotes: 13

Related Questions