2017-04-05 1 views
1

내 사용자가 두 개의 슬러그 필드 (위도, 경도)를 쿼리 한 다음 두 슬러그 필드를 비교하여 반경 1.5km 이내의 가장 가까운 거리를 찾고 가장 가까운 금고를 기준으로 API를 표시합니다. 예를 들어 : 여기에 1.5km의쿼리 REST API 위도 및 경도

내에서 사용자가 위도, 자신의 쿼리에서 경도,

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

를 추가 할 때이 표시됩니다 가장 가까운 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 루프를 실행하는 방법이 있습니까? ? 나는 현재 장고 SQLite에서 일하고있다. Views.py에서 가장 가까운 금고를 찾고 REST API로 표시하려면 나머지 api url에 사용자 입력을 사용하여 거리 함수를 구현할 수 있습니까?

답변

1

당신이 필요로하는 것은 views.py의 루프에 대한 비교를 실행하는 것입니다. 실행하기는 꽤 어렵지만 단계적으로 설명하려고 노력할 것입니다.

거리 (lat, lng, lat2, lng2) 함수를 사용하고 2km 이내에 거리를 찾으려고한다고 가정합니다. 당신은 많은 데이터가있는 경우

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) 

views.py

에서

내가 주위에 일을 판다를 사용,로드 시간이 느려질 수 있습니다. 그러나, 나는 이것이 일을한다고 생각한다. 일반적으로 Geo Django는 장거리와 위도를 처리 할 수있는 효율적인 시스템을 제공하지만 지오 장고는별로 유능하지 않으므로 실제로 알 수는 없습니다. 그러나 나는 이것이 좋은 일이라고 믿는다.

UPDATE :

당신이 당신이

+0

의미 yourapi URL을 설정하는 방법을 알고 생각

"www.yourapi.com/safeplace?lat=x = Y & LNG"를 조회 할 수 있습니다'WWW .yourapi.com/api/safeplace'? – Tushant