Reputation: 149
I am try to create a way to narrow down posts on a django app by location & radius. The way I am trying to do this is:
What I have done is successfully connect to the API, and get a lat & lng back, however I am having to filter the response in my templates rather than in my models. I have also found the following which appears to be the solution needed for narrowing results in a radius:
from django.contrib.gis.geos import Point
from django.contrib.gis.measure import Distance
lat = 52.5
lng = 1.0
radius = 10
point = Point(lng, lat)
Place.objects.filter(location__distance_lt=(point, Distance(km=radius)))
What I need to solve, and am hoping for your help with is how do I
filter the api responses and only get what I need from them (components country, geometry lat, geometry lng)
gather the lat & lng for use in the above code?
views.py
from posts import services
def search(request):
queryset_list = posts.objects.order_by('id')
if 'location' in request.GET:
q = request.GET['location']
locations_list = services.get_location(q)
context = {
'posts': queryset_list,
'locations_list': locations_list
}
return render(request, 'posts/search.html', context)
services.py
import requests
def get_location(location):
url = 'https://api.opencagedata.com/geocode/v1/json'
params = {'q': location, 'key': '###', 'language': 'en', 'pretty': 1}
r = requests.get(url, params=params)
locations = r.json()
return locations
Upvotes: 0
Views: 237
Reputation: 51998
I think you can try like this(Based on demo JSON response provided by OpenCage):
import requests
from django.db.models import Q
def get_location(location):
url = 'https://api.opencagedata.com/geocode/v1/json'
params = {'q': location, 'key': '###', 'language': 'en', 'pretty': 1}
r = requests.get(url, params=params)
locations = r.json()
filter_query = Q()
radius = 10
for item in locations.get('results', []):
geo = item.get('geometry')
lat = geo.get('lat')
lng = geo.get('lng')
point = Point(lng, lat)
filter_query |= Q(location__distance_lt=(point, Distance(km=radius)))
return Place.objects.filter(filter_query)
Upvotes: 1