简体   繁体   中英

How to use GPS location in Django REST API?

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

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM