计算距离非常慢

时间:2017-12-01 16:21:37

标签: python flask geopy

我正在开发一个向用户显示附近活动的网络应用。我有下面的代码可以工作,但它给出结果非常慢。 我想知道是否有可以让它更快。目前大约需要3秒来计算5个事件的距离。这是我的代码段。

@app.route('/events')
def events():

    events = Post.query.filter_by(event=True, trivia=False, approved=True, featured=False).order_by(Post.datetime.asc()).all()

    geolocator = Nominatim()

    if current_user.state_1 != None:
        res_state = current_user.state_1
    else:
        res_state = ','

    user_city = geolocator.geocode(current_user.city_1 + ' ' + res_state + ' ' + current_user.residence)

    user_city = (user_city.latitude, user_city.longitude)

    events_near = []

    for event in events:
        if event.address_2 != None:
            address_2 = event.address_2+','
        else:
            address_2 = ','

        if event.state != None:
            state = event.state+','
        else:
            state = ','

        if event.zip_code != None:
            zip_code = event.zip_code+'.'
        else:
            zip_code = '.'

        location = geolocator.geocode(event.address_1+',' + ' ' + address_2 + ' ' + event.city+',' + ' ' + state + ' ' + zip_code + ' ' +  event.country )
        location = (location.latitude, location.longitude)

        distance = geopy.distance.vincenty(user_city, location).miles


        if distance < dist:
            events_near.append(event)

        return render_template('events.html', events_near=events_near)

任何帮助将不胜感激。感谢。

1 个答案:

答案 0 :(得分:1)

对于想要不使用OP模块的人:

我使用了一个似乎稍微快一点的人:pygeocoder。因此,示例代码为:

from pygeocoder import Geocoder
result = Geocoder.geocode("4207 N Washington Ave, Douglas, AZ 85607")
coords = result.coordinates
print(coords) # outputs the (lat, long) of the address as a tuple

我希望任何想要使用它的人都会受到帮助!