我正在尝试根据地理位置的接近程度来检索一些帖子。
正如您在代码中看到的那样,我正在使用 GeoDjango 并且代码是在 View 中执行的。
问题是距离过滤器似乎被完全忽略了。
当我检查查询集上的距离时,我得到了预期的距离(1 米和 18 公里),但应该没有检索到 18 公里的帖子。
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也适用于 distance 查询。
如上面链接的解决方案中所述,几何字段默认为 WGS84,它以 degrees 作为默认测量单位。
0.05 度 ~= 5 km,这就是您的解决方案正常工作的原因。
也许应该通知 geodjango 团队?
