Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I query all my data within a distance of 5 meters?

I am using GeoDjango with PostGIS. Then I am into trouble on how to query my postgres db table to get all data within a distance of 5 meters.

UPDATES1 I am using GeoDjango 1.2.7

I found something from this url https://docs.djangoproject.com/en/dev/ref/contrib/gis/geoquerysets/#std:fieldlookup-distance_lte

Zipcode.objects.filter(poly__distance_lte=(geom, D(*m*=5)))

But don't know on how to prepare the parameter and variables.

  1. what is poly_distance_lte? is a function?
  2. what is geom? is a variable? how to create it?
  3. what is D? is a function? if yes, m is a parameter name of D function?
like image 663
eros Avatar asked Oct 18 '25 14:10

eros


1 Answers

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))')
like image 103
underdark Avatar answered Oct 21 '25 04:10

underdark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!