2017-07-18 136 views
2

我想檢索一些職位,取決於他們的地理位置鄰近。
正如您在代碼中看到的,我正在使用GeoDjango,代碼在視圖中執行。
問題是距離過濾器似乎被完全忽略。Geodjango距離查詢不檢索正確的結果

當我檢查查詢集的距離時,我得到預期的距離(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 

回答

1

我相信,你的問題在你點創建的reverse order of lat and lon出現。

作爲一個方面說明,我更喜歡使用的點創建Point()方法:

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

編輯由於此評論:

我試過了初始化,它對我來說似乎是正確的謝謝你。然而,它似乎沒有解決這個問題。它幾乎看起來像默認距離單位是十進制數,因爲這可以正常工作。 posts = Post.objects.filter(point__distance_lte=(pnt, 0.05))範圍5公里之內這個搜索 - 埃文

由於上述未解決您的問題,我會假設dwithin's know problem with Distance objects適用於distance查詢也是如此。

正如上面鏈接的解決方案中所述,幾何字段默認爲WGS84,其中degrees作爲默認測量單位。

0.05 degrees ~= 5 km,這就是您的解決方案正常工作的原因。

也許geodjango團隊應該被告知這個?

+0

我試過這個初始化器,對我來說似乎更正確的謝謝你。但它似乎並沒有解決這個問題。它幾乎看起來像默認距離單位是十進制數,因爲這可以正常工作。 'posts = Post.objects.filter(point__distance_lte =(pnt,0。05))'這個搜索範圍在5km以內 – Evan

+0

@Evan正如我在這裏看到的:https://epsg.io/28992,默認單位是米。我編輯了我的答案,包括對該問題的可能解釋。 –

0

相同SRID?我使用這個有很多,但與

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

然後管理器中:

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

但百達與4326

+0

是的,srid是一樣的。我有點使它的工作,但它不是很優雅。 這似乎工作'您= Post = Post.objects.filter(point__distance_lte =(pnt,米* 1e-05))' – Evan

+0

:'pnt = django.contrib.gis.geos.Point(x = 51.8125626,y = 5.8372264,srid = 28992)'? – mbieren

+0

不,我沒有嘗試過,但我不認爲問題是'pnt'因爲我在'for'循環中使用它,它提供了很好的距離。 – Evan