Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use GPS location in Django REST API?

Tags:

I am making a REST API with Django for a restaurant search app. I need to get a list of restaurants within a distance of X meters from my location. I am not sure how to store this on my database (I am using PostgreSQL) and how to retrieve this list.

I searched online some options and I found PostGIS as an extension to Postgres that can be used in Django, but I still want to listen to some of your recommendations.

Thank you

like image 283
epord Avatar asked Feb 03 '18 00:02

epord


People also ask

How do I use geo Django?

GeoDjango is an included contrib module for Django that turns it into a world-class geographic web framework. GeoDjango strives to make it as simple as possible to create geographic web applications, like location-based services. Its features include: Django model fields for OGC geometries and raster data.


1 Answers

Yes, you want to use PostGIS extension in your database, and GeoDjango in your app.

Once you have that set up and configured, use a PointField in your model. Note that you want to extend from django.contrib.gis.db.models.Model now.

from django.contrib.gis.db import models
from django.contrib.gis.geos import Point

class Restaurant(models.Model):
    point = models.PointField()

Restaurant.objects.create(point=Point(lng, lat))

To query for your restaurants, create a Point object with your lat/lng (note that GEOS takes lat/lng parameters in lng, lat order). Then use the gis D measurement for your distance query. Here is a query for restaurants within 5000 meters:

from django.contrib.gis.geos import Point
from django.contrib.gis.measure import D

my_loc = Point(my_lng, my_lat)
Restaurant.objects.filter(point__distance_lte=(my_loc, D(m=5000))
like image 60
Chris Avatar answered Sep 22 '22 12:09

Chris