Python - SqlAlchemy: Filter query by great circle distance?

后端 未结 3 1870
醉酒成梦
醉酒成梦 2021-01-07 08:24

I am using Python and Sqlalchemy to store latitude and longitude values in a Sqlite database. I have created a hybrid method for my Location object,

@hybrid_         


        
3条回答
  •  离开以前
    2021-01-07 08:51

    Obviously, you cannot get a float from that string.

    It is because you are using "self", which, as first parameter of the call, indicates that the method is a part of the object, and not some var you may pass on.

    You should try this :

    def great_circle_distance(self, first, other):
        """
        Tries to calculate the great circle distance between 
        the two locations by using the Haversine formula.
    
        If it succeeds, it will return the Haversine formula
        multiplied by 3959, which calculates the distance in miles.
    
        If it cannot, it will return None.
    
        """
        return math.acos(  self.cos_rad_lat 
                         * other.cos_rad_lat 
                         * math.cos(first.rad_lng - other.rad_lng)
                         + self.sin_rad_lat
                         * other.sin_rad_lat
                         ) * 3959
    

    I suppose here above that the global variables "self.cos_rad_lat" and "self.sin_rad_lat" are initiated with correct values somewhere else in your program, probably in the "init" section of the same object.

提交回复
热议问题