我猜想使用db.runCommand()
geoNear 查询所需的 MongoDB 在当前版本的 mongodb-enginge 中是不可能的。我现在使用具有正常近语法的 raw_query 并将 2 lat/lon 点之间的距离转换为英里(反之亦然)。
lat_lon_dist = distance_to_lat_long(dist_in_miles)
l = Listing.objects.raw_query({
'geo_location' : {
'$maxDistance': lat_lon_dist,
'$near' : { 'latitude': lat, 'longitude': lon },
}
})
...
EARTH_RADIUS = {
'km': 6371,
'mi': 3959
}
''' returns the distance between two lat/lon points in miles or kilometers '''
def lat_lon_to_distance(lat1, lon1, lat2, lon2, unit='mi'):
lat1 = math.radians(lat1)
lon1 = math.radians(lon1)
lat2 = math.radians(lat2)
lon2 = math.radians(lon2)
return math.acos(math.sin(lat1)*math.sin(lat2) +
math.cos(lat1)*math.cos(lat2) *
math.cos(lon2-lon1)) * EARTH_RADIUS[unit];
'''
converts a distance in miles or kilometer to a difference between two lat/lon points
the result is just approximately!
'''
def distance_to_lat_long(distance, unit='mi'):
return distance / math.radians(EARTH_RADIUS[unit])