对于两点之间的距离,您可以使用 Geopy。
来自documetation:
下面是 distance.distance 的一个示例用法:
>>> from geopy import distance
>>> _, ne = g.geocode('Newport, RI')
>>> _, cl = g.geocode('Cleveland, OH')
>>> distance.distance(ne, cl).miles
538.37173614757057
在 Django 项目中实现这一点。在models.py中创建一个普通模型:
class User(models.Model):
name = models.Charfield()
lat = models.FloatField()
lng = models.FloatField()
为了进行一些优化,您可以过滤用户对象以首先粗略估计附近的用户。这样您就不必遍历数据库中的所有用户。这个粗略的估计是可选的。为了满足您的所有项目要求,您可能需要编写一些额外的逻辑:
#The location of your user.
lat, lng = 41.512107999999998, -81.607044999999999
min_lat = lat - 1 # You have to calculate this offsets based on the user location.
max_lat = lat + 1 # Because the distance of one degree varies over the planet.
min_lng = lng - 1
max_lng = lng + 1
users = User.objects.filter(lat__gt=min_lat, lat__lt=max__lat, lat__gt=min_lat, lat__lt=max__lat)
# If not 20 fall back to all users.
if users.count() <= 20:
users = User.objects.all()
计算你的用户和users中每个用户的距离,按距离排序,得到前20个。
results = []
for user in users:
d = distance.distance((lat, lng), (user.lat, user.lng))
results.append( {'distance':d, 'user':user })
results = sorted(results, key=lambda k: k['distance'])
results = results[:20]