How Can I Query All My Data Within A Distance Of 5 Meters?
Solution 1:
In general, the best PostGIS function for such a query is ST_DWithin():
Returns true if the geometries are within the specified distance of one another.
eg. all customers that live within 1000 meters of shop #1:
SELECT customers.*
FROM customers, shops
WHERE ST_DWithin(customers.the_geog, shops.the_geog, 1000)
AND shop.id = 1
ST_DWithin will use the spatial index which you should have created and therefore outperform ST_Distance.
In Django there seems to be a corresponding filter called dwithin:
Returns models where the distance to the geometry field from the lookup geometry are within the given distance from one another.
Zipcode.objects.filter(poly__dwithin=(geom, D(m=5))) Backend SQL Equivalent PostGIS ST_DWithin(poly, geom, 5)
D(m=5) returns a distance object of length 5 meters
geom is the geometry from which you want to calculate distances to Zipcode objects
dwithin() is the function used
poly is the geometry attribute of Zipcode objects
z = Zipcode(code=77096, poly='POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))')
Solution 2:
I just did this a few days ago.
it is fairly hard because you should create a geography rather than a geometry point, to have access to meter unit.
so I just did it in a small extra where query
extra_where = '''
ST_Intersects(
the_geom, geometry(ST_Buffer(ST_GeographyFromText(\'%s\'), %f)))
'''
your_point = 'POINT(1 2)'
your_distance = 5 # meters
YourModule.object.filter(something).extra(where=extra_where%(your_point, your_distance))
notice the geography part and the buffer part.
Solution 3:
- what is poly__distance_lte? is a function?
The document page assumes poly
to be the name of the geometry field within your Zipcode
model. distance_lte
is just a lookup filter that finds objects within a certain distance of a point.
- what is geom? is a variable? how to create it?
It's a previously defined variable. To find Zipcode
objects with the poly
field that are within a distance of x miles from point A, you need to define point A. geom
is that definition. For example, it could be a django.contrib.gis.geos.Point
. You can set the latitude and longitude of that point and use it as the center of your search circle. In the example you obtained, this center is named geom
- what is D? is a function? if yes, m is a parameter name of D function?
D
is a class. More specifically, it's a short alias for the class called Distance
. They both can be found in django.contrib.gis.measure
. You can create an instance of this class using various real world distance metrics such as kilometers, miles, meter. In this case m is for meter.
Solution 4:
from django.contrib.gis.measure import Distance, D
d1 = Distance(km=5)
print d1
d2 = D(mi=5) # `D` is an alias for `Distance`
print d2
5.0 mi
Post a Comment for "How Can I Query All My Data Within A Distance Of 5 Meters?"