【问题标题】:Add Markers to folium map from SQLite3 table从 SQLite3 表向叶图添加标记
【发布时间】:2020-07-30 12:50:17
【问题描述】:

我正在尝试在 folium 地图上放置许多标记。坐标是从 SQLite3 表中绘制的,但现在没有显示地图,也没有抛出错误。

def maps():
    melbourne = (-37.840935, 144.946457)
    map = folium.Map(location = melbourne)
    
    try:
        sqliteConnection = sqlite3.connect('25july_database.db')
        cursor = sqliteConnection.cursor()
        print("Connected to SQLite")

        sqlite_select_query = """SELECT latitude, longitude FROM test555;"""
        
        cursor.execute(sqlite_select_query)
        
        items = cursor.fetchall()
        
        for item in items:
            folium.Marker(location = item)
            
        cursor.close()

    except sqlite3.Error as error:
        print("Failed to read data from sqlite table", error)
    finally:
        if (sqliteConnection):
            sqliteConnection.close()
            print("The SQLite connection is closed")

我尝试将“项目”设为列表 folium.Marker(location = [item]),但引发以下错误 ValueError: Expected two (lat, lon) values for location, instead got: [(-37.7650309, 144.9613659)].

这向我表明变量没有错,但其他地方有问题。

提前致谢!

【问题讨论】:

  • 所以去掉这个列表。您已经从查询中获得了元组列表。 folium.Marker(location = item) 的错误是什么?
  • 错误来自列表版本。上面块中的代码没有抛出错误,但没有显示地图,也没有标记(因为没有地图)我正在使用 Jupyter
  • 我不使用folium,但我经常使用leaflet。我强烈怀疑你误诊了这个,因为我经常遇到同样的问题。不过,我很确定将其包装在列表中的方向是错误的
  • 你会推荐传单而不是叶子吗?我认为将其包装为列表也是错误的。我只是想不出还有什么可以尝试的,否则没有错误
  • 当我没有尝试过替代方案时,我无法推荐一些东西。但我可以说传单可以掩埋错误并使其难以调试。我能给出的唯一有用的建议是,在我看来,列表方法是不正确的。我相信其他人可以为您解决问题

标签: python sqlite geocoding folium


【解决方案1】:

为了从列表中提取元组(-37.7650309, 144.9613659),您只需要获取第一个元素:folium.Marker(location = item[0])

您还需要在地图上添加标记:folium.Marker(location = item[0]).add_to(map)

为了绘制地图,您需要在函数结束时返回它。

你会得到这样的东西(它在我的 Jupyter Notebook 中工作):

def maps():
    melbourne = (-37.840935, 144.946457)
    map = folium.Map(location = melbourne)
    
    try:
        sqliteConnection = sqlite3.connect('25july_database.db')
        cursor = sqliteConnection.cursor()
        print("Connected to SQLite")

        sqlite_select_query = """SELECT latitude, longitude FROM test555;"""
        
        cursor.execute(sqlite_select_query)
        
        items = cursor.fetchall()
        
        for item in items:
            folium.Marker(location = item[0]).add_to(map)
            
        cursor.close()

    except sqlite3.Error as error:
        print("Failed to read data from sqlite table", error)
    finally:
        if (sqliteConnection):
            sqliteConnection.close()
            print("The SQLite connection is closed")
    return map

注: 您不应该使用 map 作为变量的名称,因为您隐藏了 Python 标准库的 map() 函数。

【讨论】:

  • 非常感谢,我还必须将“cursor.fetchall()”元素转换为列表,然后才能执行您建议的部分!
猜你喜欢
  • 2019-05-22
  • 2015-08-06
  • 2019-03-07
  • 1970-01-01
  • 1970-01-01
  • 2020-06-15
  • 2019-05-31
  • 2017-04-26
  • 1970-01-01
相关资源
最近更新 更多