首页 > 解决方案 > 从 SQLite3 表向叶图添加标记

问题描述

我正在尝试在 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)].

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

提前致谢!

标签: pythonsqlitegeocodingfolium

解决方案


为了(-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你的变量名,因为你隐藏map()了 Python 标准库的函数。


推荐阅读