【发布时间】:2018-03-25 16:18:00
【问题描述】:
我已经使用 postgis 和 geodjango 实现了从给定坐标显示附近餐厅的功能。但是我需要根据用户附近的距离或给定的坐标找到以公里或米为单位的距离。我知道在 SO 中提出了与距离相关的问题,但这个问题有点不同。我正在显示餐厅列表(列表视图)而不是餐厅的详细信息,我将从 id 获得特定的餐厅位置。所以我需要一个想法,我现在应该如何在餐厅列表视图中显示每家餐厅的距离。
我的想法是我应该通过 lat 和 lng(我从 url 传递)作为上下文并使用模板过滤器来计算距离
from django.contrib.gis.geos import GEOSGeometry
pnt = GEOSGeometry('SRID=4326;POINT(40.396764 -3.68042)')
pnt2 = GEOSGeometry('SRID=4326;POINT( 48.835797 2.329102 )')
pnt.distance(pnt2)*100
这里是详细代码
def nearby_restaurant_finder(request, current_lat, current_long):
from django.contrib.gis.geos import Point
from django.contrib.gis.measure import D
user_location = Point(float(current_long), float(current_lat))
distance_from_point = {'km': 500}
restaurants = Restaurant.gis.filter(
location__distance_lte=(user_location, D(**distance_from_point)))
restaurants = restaurants.distance(user_location).order_by('distance')
context = {
'restaurants': restaurants
}
return render(request, 'restaurant/nearby_restaurant.html', context)
url(r'^nearby_restaurant/(?P<current_lat>-?\d*.\d*)/(?P<current_long>-?\d*.\d*)/$',
views.nearby_restaurant_finder, name="nearby-restaurant"),
{% block page %}
{% for restaurant in restaurants %}
<h1>Nearby Restaurants are:</h1>
<h3>{{ restaurant.name }}</h3>
{% empty %}
<h3>No Match Found</h3>
{% endfor %}
{% endblock %}
请分享您对我应该如何做的想法
【问题讨论】:
标签: python django django-views postgis