GeoJSON#

Example#

import os
import json
import random
import requests

from ipyleaflet import Map, GeoJSON

if not os.path.exists('europe_110.geo.json'):
    url = 'https://github.com/jupyter-widgets/ipyleaflet/raw/master/examples/europe_110.geo.json'
    r = requests.get(url)
    with open('europe_110.geo.json', 'w') as f:
        f.write(r.content.decode("utf-8"))

with open('europe_110.geo.json', 'r') as f:
    data = json.load(f)

def random_color(feature):
    return {
        'color': 'black',
        'fillColor': random.choice(['red', 'yellow', 'green', 'orange']),
    }

m = Map(center=(50.6252978589571, 0.34580993652344), zoom=3)

geo_json = GeoJSON(
    data=data,
    style={
        'opacity': 1, 'dashArray': '9', 'fillOpacity': 0.1, 'weight': 1
    },
    hover_style={
        'color': 'white', 'dashArray': '0', 'fillOpacity': 0.5
    },
    style_callback=random_color
)
m.add(geo_json)

m

Usage#

The GeoJSON layer is a widget, which means that you can update the data or any other attribute from Python and it will dynamically update the map:

geo_json.data = new_data
geo_json.hover_style = new_hover_style

Attributes and methods#

class ipyleaflet.leaflet.GeoJSON(**kwargs: Any)[source]#

GeoJSON class, with FeatureGroup as parent class.

Layer created from a GeoJSON data structure.

data#

The JSON data structure.

Type:

dict, default {}

style#

Extra style to apply to the features.

Type:

dict, default {}

hover_style#

Style that will be applied to a feature when the mouse is over this feature.

Type:

dict, default {}

point_style#

Extra style to apply to the point features.

Type:

dict, default {}

style_callback#

Function that will be called for each feature, should take the feature as input and return the feature style.

Type:

callable, default None

on_click(callback, remove=False)[source]#

Add a feature click event listener.

Parameters:
  • callback (callable) – Callback function that will be called on click event on a feature, this function should take the event and the feature as inputs.

  • remove (boolean) – Whether to remove this callback or not. Defaults to False.

on_hover(callback, remove=False)[source]#

Add a feature hover event listener.

Parameters:
  • callback (callable) – Callback function that will be called when the mouse is over a feature, this function should take the event and the feature as inputs.

  • remove (boolean) – Whether to remove this callback or not. Defaults to False.