python - 计算距离很慢

标签 python flask geopy

我正在开发一个网络应用程序,可以向用户显示他们附近的事件。我有下面的代码可以工作,但给出结果的速度非常慢。 我想知道是否有什么办法可以让它更快。目前仅计算 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

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

关于python - 计算距离很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47597407/

相关文章:

Python igraph 顶点索引

python - 查找列表中最大的匹配项

python - Flask-如何从查询中抑制 "None"

python - 在 Knockout attr 绑定(bind)下使用 Jinja2 模板

python - 位置之间的地理距离

python - 获取 DataFrame 的不同输出和相同代码的正常实现

python - 使用 Sublime 获取光标下的单词

python - 如何使用变形网格扭曲图像

python - Flask JWT 扩展缺少 csrf 访问 token

python - 有没有比 for 循环和 if 语句更快的方法来找到距 python 中另一个点最近的点?