简体   繁体   中英

How to filter objects with LineString field by distance to a Point?

I have a model with a LineStringField , which represents a path, as such:

class Link(models.Model):
    # Non-relevant fields omitted
    geometry = models.LineStringField(srid=3067)

Now, I'd like to query for objects where the distance of any point in the line string is less than a given distance (say, 100 meters).

I've tried this query:

lat = float(self.request.query_params['lat'])
lon = float(self.request.query_params['lon'])
point = Point(lat, lon, srid=4326)
return Link.objects.filter(geometry__distance_lt=point, 100)

However, this yields zero results, even if I increase the distance limit to hundreds of kilometers (all the test data is within about 50 km from the given lat/lon point). Is there something wrong in my query?

To solve these kind of problems we usually create a buffer geometry (a polygon) around the line and then intersect this geometry with your points.

Buffer in DB (didn't find it in geodjango functions, maybe it's there.) https://postgis.net/docs/ST_Buffer.html

See doc for creating buffer with GEOS https://django.readthedocs.io/en/stable/ref/contrib/gis/geos.html#django.contrib.gis.geos.GEOSGeometry.buffer

Intersection filter https://docs.djangoproject.com/en/3.1/ref/contrib/gis/geoquerysets/#std:fieldlookup-dwithin

After a frustrating debugging session, I found out that latitude and longitude have to be passed in opposite order when constructing a Point :

lat = float(self.request.query_params['lat'])
lon = float(self.request.query_params['lon'])
point = Point(lon, lat, srid=4326)
return Link.objects.filter(geometry__distance_lt=point, 100)

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