Geodjango distance query not retrieving correct results

岁酱吖の 提交于 2019-12-24 03:12:44

问题


I am trying to retrieve some posts depending on their proximity geographically.
As you can see in the code I am using GeoDjango and the code is executed within a view.
The issue is that the distance filter seems to be completely disregarded.

When I check the distances on the queryset I get the expected distances (1m and 18km) but the 18km post should not have been retrieved.

def get(self, request, format=None):
    latlon=request.query_params
    pnt = GEOSGeometry('SRID=28992;POINT(%s %s)'%(latlon['lat'],latlon['lon']))
    posts = Post.objects.filter(point__distance_lte=(pnt, D(km=1)))
    serialized = PostSerializer(posts, many=True)
    for post in posts:
        distance = pnt.distance(post.point)
        print("Km distance:",distance * 100)
    return JsonResponse(serialized.data, safe=False)

Result:

Km distance: 0.00015231546206626192
Km distance: 18.317378752081577
[18/Jul/2017 13:24:35] "GET /api/posts/?lon=5.8372264&lat=51.8125626 HTTP/1.1" 200 144

回答1:


I believe that your problem arises from the reverse order of lat and lon in your point creation.

As a side note, I prefer to use the Point() method for point creation:

ptn = Point(x=latlon['lon'], y=latlon['lat'], srid=28992)

Edit due to this comment:

I tried that initializer, it seems correct to me thank you. However it doesn't seem to have solved the issue. It almost looks as the default distance unit is decameters because this works correctly. posts = Post.objects.filter(point__distance_lte=(pnt, 0.05)) this searches within a range of 5km – Evan

Since the above didn't solve your problem, I will assume that the dwithin's know problem with Distance objects apply to the distance queries as well.

As stated in the solution linked above, geometry fields default to WGS84 which have degrees as a default measurement unit.

0.05 degrees ~= 5 km, and that is why your solution worked correctly.

Maybe the geodjango team should be informed of this?




回答2:


Same SRID ? I am using this a lot but with

source = models.PointField(geography=True, srid=4326)

and then within a manager :

def starts_within_range_of(self, my_start, distance):
    ret_value = self.filter(
        source__distance_lte=(my_start, distance))
    return ret_value

But allways with 4326



来源:https://stackoverflow.com/questions/45165491/geodjango-distance-query-not-retrieving-correct-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!