Search code examples
pythonsqlitegeocodingfolium

Add Markers to folium map from SQLite3 table


I am trying to drop many markers on a folium map. The coordinates are drawn from a SQLite3 Table but right now no map is displaying and no error is being thrown.

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

I tried to make "item" a list folium.Marker(location = [item]) but that threw the following error ValueError: Expected two (lat, lon) values for location, instead got: [(-37.7650309, 144.9613659)].

This suggests to me that the variable is not wrong but something else is broken somewhere.

Thanks in advance!


Solution

  • In order to extract the tuple (-37.7650309, 144.9613659) from the list, you just need to take the first element : folium.Marker(location = item[0])

    You also need to add the marker to the map : folium.Marker(location = item[0]).add_to(map)

    In order to draw the map, you need to return it at the end of your function.

    You will have something like this (it works in my 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: You should not use map as the name of your variable because you shadow the map() function of the Python standard library.