pythonpython-3.xipyleaflet

ipyleaflet on_click event in for loop calls function on each iteration


I've been plotting markers on a map, each with its own location and sample id. I'm trying to add a click_event on each marker so that each marker will print out its sample Id upon being clicked. My main issue is with the on_click event, which seems to call the button_click function with each iteration before I even get to click the marker.

capitol_loc = (38.89, -77.02) #(lat, long)
m = Map(center=(capitol_loc), zoom=14)
locations = [(38.89, -77.02), (38.88, -77.02), (38.88, -77.01), (38.873, -77.02), (38.891, -77.02), (38.89, -77.022)]

def button_click(sample_id):
    print(str(sample_id))


for i in range(len(locations)):
    new_marker_loc = (locations[i][0], locations[i][1])
    new_marker = Marker(location=new_marker_loc, draggable=False)
    
    sample_id = "Sample Id: 1234567"
    
    new_marker.on_click(button_click(sample_id)) 
    m.add_layer(new_marker)
    
m  #Display map

Output: enter image description here

One strange thing I noticed was that if I set the on_click event to call a function without a parameter (simple "hello world" function in this case), it worked with no problems however, I need a parameter from within the for loop,


Solution

  • One possible solution is to create a function that returns the appropriate function:

    def create_button_click(val):
        def button_click():
            print(val)
        
        return button_click
    

    Then you can pass this returned function to the marker on_click event:

    new_marker.on_click(create_button_click(val))