Ipyleaflet: how to use right-click in notebook in browser?

43 views Asked by At

Context:

I have an interactive map. If you 'right-click' inside a shape (outlined in bright green), it highlights this shape in blue and appends information related to the shape, to a list (as a geopandas dataframe). (see picture) enter image description here

Problem:

This code works on vscode, but if I used a browser-based notebook, 'right-click' (contextmenu in the code) triggers the popup of the page's options (see picture) enter image description here.

While the information is still appended to my list of geopandas dataframes, it does not highlight the shape in blue.

Ideas:

I thought of 2 ways of getting rid of this issue:

  • Change the right-click interaction to a middle-click (or typing a letter on the keyboard)
  • Remove the popup of the webpage on right-click

But with ipyleaflet, a 'left-click' and a 'middle click' (click with the scroll wheel) are not possible to distinguish one from the other.

Any idea about how I could tackle this issue ?

Code:

from ipyleaflet import Map, WMSLayer, basemaps
from ipywidgets import HTML
from owslib.wms import WebMapService


# Address for the wms layer
wms_url = "https://glims.org/geoserver/ows?SERVICE=WMS&"
wms_layer = WMSLayer(
    url=wms_url,
    layers='GLIMS:RGI',
    transparent=True,
    format='image/png'
)


# Create a Pandas DataFrame with X and Y coordinates
#data = pd.DataFrame({'X': list(fx_map[::50]), 'Y': list(fy_map[::50])})

# Map and label widgets
map = ipyl.Map(basemap=basemaps.Esri.WorldImagery, center=(0, 0), zoom=2)
label = ipyw.Label(layout=ipyw.Layout(width="100%"))

# Create a list to store clicked URLs
urls = []

wms = WebMapService(wms_url)

# Initialize a list to store the geopandas dataframes
gdf_list = []

# Create a function to handle click events
def click_handler(properties=None, **kwargs):
    
    
    # Uncomment if you want to print all possible operations with mouse
    #print(kwargs.get('type'))   

    # If right-click, then do all that
    if kwargs.get('type') == 'contextmenu':
        latlon = kwargs.get('coordinates')
        lat, lon = latlon[0], latlon[1]
        print(f"Clicked at (Lat: {lat}, Lon: {lon})")
        
        # Get feature info of the shape clicked-on
        response = wms.getfeatureinfo(
            layers=['GLIMS:RGI'],
            srs='EPSG:4326',
            bbox=(lon-0.001,lat-0.001,lon+0.001,lat+0.001),
            size=(1,1),
            format='image/jpeg',
            query_layers=['GLIMS:RGI'],
            info_format="application/json",
            xy=(0,0))

        # Download the features in a geopandas dataframe
        df = gpd.read_file(response)
        # Append the dataframe to the list of dataframes
        gdf_list.append(df)  

        # If shape has no info the script still runs
        try:
            print(f"You have selected the glacier {df['NAME'].values[0]}, ID: {df['id'].values[0]} ")
        except:
            print(f"This glacier is not recognized by the RGI (maybe an ice-shelf ?) -> Choose another one")

        # PCreate the layer for the blue shape that was clicked on
        geo_data = GeoData(geo_dataframe = df,
                   style={'color': 'black', 'fillColor': '#3366cc', 'opacity':0.05, 'weight':1.9, 'dashArray':'2', 'fillOpacity':0.6},
                   hover_style={'fillColor': 'blue' , 'fillOpacity': 0.2},
                   name = 'Glacier')
        # Add the blue shape to the map
        map.add_layer(geo_data)
        gdf_list.append(df)  

        



# Enable zoom when scrolling with the mouse
map.scroll_wheel_zoom = True
ipyw.VBox([map, label])


# Add the WMS layer to the map
map.add_layer(wms_layer)

# Add the click event handler to the map
map.on_interaction(click_handler)

map
0

There are 0 answers