Skip to content

10 add vector

image image image

Adding local vector data (e.g., shp, geojson, kml) to the map

Uncomment the following line to install leafmap if needed.

1
# !pip install leafmap
1
import leafmap
1
2
m = leafmap.Map()
m

This demo is based on the ipyleaflet plotting backend. The folium plotting backend does not have the interactive GUI for loading local vector data.

Add a GeoJSON to the map.

1
2
3
4
5
6
7
8
m = leafmap.Map(center=[0, 0], zoom=2)

in_geojson = (
    "https://github.com/opengeos/datasets/releases/download/vector/cables.geojson"
)
m.add_geojson(in_geojson, layer_name="Cable lines")

m

Add a GeoJSON with random filled color to the map.

1
2
3
4
5
6
m = leafmap.Map(center=[0, 0], zoom=2)
url = "https://raw.githubusercontent.com/opengeos/leafmap/master/examples/data/countries.geojson"
m.add_geojson(
    url, layer_name="Countries", fill_colors=["red", "yellow", "green", "orange"]
)
m

Use the style_callbackfunction for assigning a random color to each polygon.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import random

m = leafmap.Map(center=[0, 0], zoom=2)

url = "https://raw.githubusercontent.com/opengeos/leafmap/master/examples/data/countries.geojson"


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


m.add_geojson(url, layer_name="Countries", style_callback=random_color)
m

Use custom style and hover_style functions.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
m = leafmap.Map(center=[0, 0], zoom=2)

url = "https://raw.githubusercontent.com/opengeos/leafmap/master/examples/data/countries.geojson"

style = {
    "stroke": True,
    "color": "#0000ff",
    "weight": 2,
    "opacity": 1,
    "fill": True,
    "fillColor": "#0000ff",
    "fillOpacity": 0.1,
}

hover_style = {"fillOpacity": 0.7}

m.add_geojson(url, layer_name="Countries", style=style, hover_style=hover_style)
m

Add a shapefile to the map.

1
2
3
4
5
6
m = leafmap.Map(center=[0, 0], zoom=2)

in_shp = "../data/countries.shp"
m.add_shp(in_shp, layer_name="Countries")

m

Add a KML to the map.

1
2
3
4
5
6
m = leafmap.Map()

in_kml = "../data/us_states.kml"
m.add_kml(in_kml, layer_name="US States KML")

m

The add_vector function supports any vector data format supported by GeoPandas.

1
2
3
4
5
6
m = leafmap.Map(center=[0, 0], zoom=2)
url = "https://raw.githubusercontent.com/opengeos/leafmap/master/examples/data/countries.geojson"
m.add_vector(
    url, layer_name="Countries", fill_colors=["red", "yellow", "green", "orange"]
)
m
1
m = leafmap.Map()
1
2
3
in_shp = "../data/countries.shp"
in_geojson = "../data/us_states.json"
in_kml = "../data/us_states.kml"
1
m.add_shp(in_shp, layer_name="Shapefile")
1
m.add_geojson(in_geojson, layer_name="GeoJSON")
1
m.add_kml(in_kml, layer_name="KML")
1
m