GeoPandas

This page explores the GeoPandas library. This is an extention of the commonly used Pandas library with geospatial support added. It is handy for exploring and manipulating geospatial data in Jupyter notesbooks. In this instance I am just using in the Django backend of this site rather that attempting to incorporate notebooks into this site - or maintain externally hosted notebooks.

GeoPandas can be found at: https://geopandas.org/en/stable/index.html

NOTE: This page is still a work in progress.


Reading from Features

In this example I serialize data from the database using the Django geojson serializer and then use the from_features method to bring this into GeoPandas. Unfortunately this crashes. I am not investigating this further at present but will leave in here in the hope it is a bug that gets resolved.

NOTE: if I print the serialised data to console then paste this into the backend as a variable with the json then it works. very peculiar.

    

    venues = serialize(
        "geojson",
        Venue.objects.all()[:2],
        geometry_field="geom",
        fields=["name", "capacity"],
        id_field="id",
    )

    df = gpd.GeoDataFrame.from_features(venues)

       

Basic usage

In this example a shapefile is loaded using the read_file() method. We then take the first item using "iloc". This is then output to a map in folium.

    

    #example -> Path from pathlib library
    shp_path = Path(__file__).resolve().parent / "dirname" / "filename.shp"

    if shp_path.exists():

        df = gpd.read_file(shp_path)

        # get the first item
        first_item = df["geometry"].iloc[0]

        # output on a folium map
        m = folium.Map(zoom_start=10, tiles=None)
        sim_geo = gpd.GeoSeries(first_item).simplify(tolerance=0.001).to_json()
        folium.GeoJson(
            data=sim_geo, 
            style_function=lambda x: {"fillColor": "orange"}
        ).add_to(m)

        context["map"] = m._repr_html_()