2017-04-05 108 views
1

我希望我的用戶查詢兩個slugs字段(緯度,經度),然後將2個slug字段進行比較,以找到1.5km半徑範圍內的最近距離,並根據最近的安全屋顯示api。 例如:當用戶添加經度,緯度在查詢中,查詢REST API經緯度

  www.example.com/safeplace/?find=-37.8770,145.0442 

這會顯示內1.5公里

這裏最近的safeplaces是我的功能

def distance(lat1, long1, lat2, long2): 
    R = 6371 # Earth Radius in Km 
    dLat = math.radians(lat2 - lat1) # Convert Degrees 2 Radians 
    dLong = math.radians(long2 - long1) 
    lat1 = math.radians(lat1) 
    lat2 = math.radians(lat2) 
    a = math.sin(dLat/2) * math.sin(dLat/2) + math.sin(dLong/2) * 
    math.sin(dLong/2) * math.cos(lat1) * math.cos(lat2) 
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a)) 
    d = R * c 
    return d 

這裏是我的模型

class Safeplace(models.Model): 
    establishment = models.CharField(max_length=250) 
    address = models.CharField(max_length=250) 
    suburb = models.CharField(max_length=250) 
    postcode = models.IntegerField() 
    state = models.CharField(max_length=250) 
    type = models.CharField(max_length=250) 
    latitude = models.DecimalField(decimal_places=6,max_digits=10) 
    longtitude = models.DecimalField(decimal_places=6,max_digits=10) 

有沒有辦法在我的數據庫中運行for循環?我目前正在研究Django SQLite。在Views.py上,如何在用戶輸入中實現距離函數,在我的rest api url中查找最近的safeplace並顯示爲REST Api?

回答

1

你需要的是在你的views.py中運行循環比較。這是很難執行,但我會嘗試一步一步解釋。例如,假設您正在使用該距離(lat,lng,lat2,lng2)函數並試圖找到距離2km以內的距離。

在views.py

import pandas as pd 
class someapiview(ListAPIView): 
    serializer_class = SafeplaceSerializer 
### Now we are creating definition which sorts parameters lng and lat ### 
    def get_queryset(self): 
     queryset = Safeplace.Objects.all() 
     lat = float(self.query_params.get('lag', None) 
     lng = float(self.query_params.get('lng', None) 
     ### Now, we are reading your api using pandas ### 
     df = pd.read_json('yourapi') ## yourapi is a url to ur api 
     obj = [] 
     for x in range(0, len(df)): 
      latx = float(df['latitude'][x]) 
      lngx = float(df['longitude'][x]) 
      ### Calculating distance ### 
      km = distance(lat, lng, latx, lngx) 
      if km <= 2: 
       obj.append(df['id'][x]) 
     ### Django auto generate primary key which usually calls id ### 
     ### Now we are going to call those pk as a queryset ### 
     return Safeplace.objects.filter(pk__in=obj) 

我用熊貓來解決,如果你有很多數據的加載時間可能很慢。不過,我認爲這是做這個工作。通常Geo Django提供了一個高效的系統來處理long和lat,但是我對Geo Django不是很有能力,所以我無法真正瞭解。但我相信這是一個很好的解決方案。

UPDATE:

你可以查詢 「www.yourapi.com/safeplace?lat=x & LNG = Y」

我相信你知道如何設置的URL

+0

yourapi表示'WWW .yourapi.com/api/safeplace'? – Tushant