1キロ以内の最大最小の緯度を計算する&&地球上の2点間の距離を計算するpython

2186 ワード

一緒にプレイアプリを開発する際に、距離のある処理をして、これを整理します.
  • xキロメートルの範囲内の最大最小緯度を計算し、データベースからデータ
  • を取得する.
    phpメソッド:
    $myLat = $postObj->Location_X;//           
    $myLng = $postObj->Location_Y;//           
    
    $Label = $postObj->Label;//            
    $Label = iconv("UTF-8","GBK",$Label);
    $find = stripos($Label,' ');//               
    if($find!==false)
    {
        $Label = substr($Label,0,$find);
    }
    
    //       
    $range = 180 / pi() * 1 / 6372.797;     //    1       1km   ,  km
    $lngR = $range / cos($myLat * pi() / 180);
    $maxLat = $myLat + $range;//    
    $minLat = $myLat - $range;//    
    $maxLng = $myLng + $lngR;//    
    $minLng = $myLng - $lngR;//    
    //        ,                      ~

    pythonメソッド:
    import math
    #   x              
    def calcu_location(location_x, location_y, r=1):
        lat_range = 180 / math.pi * r / 6372.797  #     1       1km   ,  km
        long_r = lat_range / math.cos(location_x * math.pi / 180)
        max_lat = location_x + lat_range  #     
        min_lat = location_x - lat_range  #     
        max_long = location_y + long_r  #     
        min_long = location_y - long_r  #     
        
        range_xy = {}
        range_xy['location_x'] = {'min':min_lat, 'max':max_lat}
        range_xy['location_y'] = {'min':min_long, 'max':max_long}
        return range_xy

    テスト:
    print calcu_location(-30.376393,-114.33879)

    出力:
    {'location_x': {'max': -30.367402319846047, 'min': -30.385383680153954}, 'location_y': {'max': -114.32836870647137, 'min': -114.34921129352864}}

    2.地球上の2点間の距離、単位キロメートルを計算する
    pythonメソッド:
    #      ,       ,    :  
    def rad(flo):
        return flo * math.pi / 180.0
        
    def calcu_distance(lat1,lng1,lat2,lng2):
        earth_radius=6378.137
        radlat1=rad(lat1)
        radlat2=rad(lat2)
        a=radlat1-radlat2
        b=rad(lng1)-rad(lng2)
        s=2*math.asin(math.sqrt(math.pow(math.sin(a/2),2)+math.cos(radlat1)*math.cos(radlat2)*math.pow(math.sin(b/2),2)))
        s=s*earth_radius
        if s<0:
            return round(-s,2)
        else:
            return round(s,2)