我正在尝试根据地理位置的接近程度来检索一些帖子。
正如您在代码中看到的,我正在使用 GeoDjango 并且代码在 View 中执行。
问题是距离过滤器似乎被完全忽略了。
当我检查查询集上的距离时,我得到了预期距离(1m 和 18km),但 18km 的帖子不应该被检索到。
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)
结果:
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
最佳答案
我相信您的问题源于 reverse order of lat
and lon
在您的点创建中。
顺便说一句,我更喜欢使用 Point()
点创建方法:
ptn = Point(x=latlon['lon'], y=latlon['lat'], srid=28992)
根据此评论进行编辑:
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
由于上述方法没有解决您的问题,我假设dwithin
's know problem with Distance
objects也适用于距离
查询。
如上面链接的解决方案中所述,几何字段默认为 WGS84,其默认测量单位为度
。
0.05 度 ~= 5 km
,这就是您的解决方案正常工作的原因。
也许 geodjango 团队应该被告知这一点?
关于python - Geodjango距离查询未检索到正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45165491/