计算距离很慢

Calculating distance is very slow

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

@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)

如有任何帮助,我们将不胜感激。谢谢

对于不想使用 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

我希望对任何想使用它的人有所帮助!