如何过滤具有纬度和纬度坐标的django模型,该坐标位于一定半径范围内 [英] How to filter a django model with latitude and longitude coordinates that fall within a certain radius
问题描述
我有以下模型。
class Location(models.Model):
name = models.CharField (max_length = 128,blank = True)
address = models.CharField(max_length = 200,blank = True)
latitude = models.DecimalField(max_digits = 6,decimal_places = 3)
经度= models.DecimalField(max_digits = 6,decimal_places = 3)
def __unicode __(self):
return self.name
如果我当前的纬度&经度是:
current_lat = 43.648
pre>
current_long = 79.404
我做了一些研究,发现了
I have the following model.
class Location(models.Model): name = models.CharField(max_length = 128, blank = True) address =models.CharField(max_length = 200, blank= True) latitude = models.DecimalField(max_digits=6, decimal_places=3) longitude = models.DecimalField(max_digits=6, decimal_places=3) def __unicode__(self): return self.name
If my current latitude & longitude is:
current_lat = 43.648 current_long = 79.404
I did some research and came across the Haversine Equation which calculates the distance between two location coordinates. Below is the equation I found:
import math def distance(origin, destination): lat1, lon1 = origin lat2, lon2 = destination radius = 6371 # km dlat = math.radians(lat2-lat1) dlon = math.radians(lon2-lon1) a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) \ * math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a)) d = radius * c return d
I would like to return all the Location objects that fall within a 10 km radius, how can I filter it in such a way that it will only return all the Location objects that fall within this 10 km radius?
LocationsNearMe = Location.objects.filter(#This is where I am stuck)
Is there anyway I can implement the Haversine equation into the filtering so that it only returns the location objects that fall within a 10 km radius?
I'm looking for a well detailed answer. Appreciate the help.
解决方案But you can always make proposed by Brian approach better by filtering the results from previous step (which hoepfully should be smaller subset) and for each you check either they are within the radius.
Your user is in black point. Square approximation given by Brian return green but also orange points. The divernce in distance can be significant in worst case user have to go sqrt(2) times further than expected (extra 40% of distance). So for all orange and green points it is worth to check if their distance from black point (e.g euclidian one if this are really short distances e.g navigation in city) is not greater than assumed radius.
UPDATE:
If you would like to use Haversine distance or (better) mentioned GeoDjango hava a look on this snippet comparing two django views dealing with nearby search:
https://gist.github.com/andilabs/4232b463e5ad2f19c155
这篇关于如何过滤具有纬度和纬度坐标的django模型,该坐标位于一定半径范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!