Skip to content

Instantly share code, notes, and snippets.

@SanskarSans
Last active October 13, 2017 15:51
Show Gist options
  • Save SanskarSans/fe05e1d28552b9f5cc077e0ffa23a2f4 to your computer and use it in GitHub Desktop.
Save SanskarSans/fe05e1d28552b9f5cc077e0ffa23a2f4 to your computer and use it in GitHub Desktop.
# credit - zsoobhan from SO (https://stackoverflow.com/questions/46731426/show-distance-in-km-or-m-of-each-restaurant/46732398#46732398)
def calculate_distance(restaurant, current_lat, current_long):
from django.contrib.gis.geos import GEOSGeometry
pnt = GEOSGeometry(restaurant.location)
pnt2 = GEOSGeometry('SRID=4326;POINT({0} {1})'.format(
current_long, current_lat))
print(pnt.distance(pnt2) * 100)
return round(pnt.distance(pnt2) * 100, 2)
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')
ctx_restaurants = [
{
'name': restaurant.name,
'distance_from_user': calculate_distance(restaurant, current_lat, current_long)
}
for restaurant in restaurants
]
context = {
'restaurants': ctx_restaurants
}
return render(request, 'restaurant/nearby_restaurant.html', context)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment