I have a Django application that needs to filter users by location (show users who are within a given distance of the logged in user).
Right now I am able to capture the logged in users latitude and longitude coordinates using HTML5 and save them into the Location table in my SQLite backend.
I have the GeoIP2 lists with city and country in a folder in my project, I'm not sure how I can use them but they seem to be a good option as they take in lat and lon coordinates and generate out a location.
I know there are a few options here, for example making a point value from the lat lon coordinates, which would then perhaps be able to filter by radius? Etc, 5km, 10km, 15km?
I'm relatively new to all of this which is why I am asking for a clean minimal solution.
I do not want to use PostGres, GIS, GeoDjango.
If someone has a simple solution for doing this using Sqlite and possibly the geoip2 lists, I would very much appreciate you sharing it!
models.py
class Location(models.Model):
latitude = models.DecimalField(max_digits=19, decimal_places=16)
longitude = models.DecimalField(max_digits=19, decimal_places=16)
user = models.OneToOneField(User, on_delete=models.CASCADE, null=False, related_name='loc')
def __str__(self):
return f'{self.user}\'s location'
@login_required
def insert(request):
location = Location(latitude=request.POST['latitude'],
longitude=request.POST['longitude'], user = request.user)
location.save()
return JsonResponse({'message': 'success'})
def location_view(request):
queryset = User.objects.annotate(
radius_sqr=pow(models.F('loc__latitude') -
request.user.loc.latitude, 2) + pow(models.F('loc__longitude') -
request.user.loc.longitude, 2)
).filter(
radius_sqr__lte=pow(radius_km / 9, 2)
)
return django.shortcuts.render_to_response(request, context, 'connect/home.html')
location page.html example
{% for user in location %}
<h5><b>{{ user.first_name }} {{ user.last_name }}</b></h5>
{% endfor %}