从SQLite3表向folium映射添加标记

时间:2020-07-30 12:50:17

标签: python sqlite geocoding 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)].

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

谢谢!

1 个答案:

答案 0 :(得分: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

N.B: 您不应使用map作为变量的名称,因为它会遮盖Python标准库的map()函数。

相关问题