问题
I've got a large number of points (~1.5 million) in the WGS84 coordinate system. The points span a large area, so I can't use a projected coordinate system. I want to find the closest point to a given pair of input coordinates. I have a working view, but it takes too long (~2.5 seconds) to execute.
This is my model:
from django.contrib.gis.db import models
class Point(models.Model):
id = models.IntegerField(primary_key=True)
geom = models.PointField(srid=4326, spatial_index=True)
objects = models.GeoManager()
This is the query in the view (which I got from another SO question):
input_point = GEOSGeometry('POINT({0} {1})'.format(lon, lat))
point = Point.objects.distance(input_point).order_by('distance')[0]
Is there a way to do this faster? I have an equivalent query in SQLAlchemy/GeoAlchemy2, which takes less than 0.5 seconds to execute, so I know it's possible.
from geoalchemy2.elements import WKTElement
pt = WKTElement('POINT({0} {1})'.format(lon, lat), srid=4326)
q = session.query(Point).order_by(Point.geom.distance_box(pt)).first()
Is there a better way to do "nearest point" queries with GeoDjango?
回答1:
Not sure, this may be faster. You can use the google projection (900913
) to get your data in meters.
from django.contrib.gis.measure import D
DISTANCE_LIMIT_METERS = 5000
input_point = Point(lon, lat, srid=4326)
input_point.transform(900913)
ModelContainingPoint.objects.filter(geom__dwithin=(input_point , D(m=DISTANCE_LIMIT_METERS)))
Reference:
https://docs.djangoproject.com/en/dev/ref/contrib/gis/db-api/#distance-queries
来源:https://stackoverflow.com/questions/15915801/fastest-way-to-get-nearest-geometry-to-a-point-in-geodjango