Display a polygonized raster in a Django Webapp (2/2): Show the polygons in a Mapbox
This tutorial is a follow up to a previous tutorial in which we saw how to polygonize a raster with rasterio, and save the polygons produced to a PostGIS database associated with a Django webapp we have developed. In this tutorial, we’ll simply display the polygons created with Mapbox on a front-end Django template.
First things first, we begin by adding the route to the Django view we’ll create later to”<my-app>/urls.py”. The Django app was called “maps” in the previous tutorial:
After that, we create a view function in “<my-app>/views.py” called “list()”. You might’ve noticed that the second parameter we passed to the url route is a reference to this view function. The view function gets the HttpRequest as a parameter and returns as an HttpResponse the template to show when the user browses to the route above:
Inside this view function, we’re going to do a query to get all the polygons that were saved in the “Flood” database table in the previous tutorial. I found out that Mapbox accepts as an argument a string variable formatted as GeoJSON. To put our variable in the correct format, below I’m going through all the geometry entries in the database table to eventually add them to a Multi-Polygon variable. In the last line of the code below, we’re telling the view to render the template (“maps/flood-list.html”), to which we’re passing the Multi-Polygon:
Don’t forget to import at the top of the view.py file all the functions we’ve utilized above:
We move on to the template file we create inside the Django app folder, precisely in “maps/templates/maps/flood-list.html”. Inside the template we need to first and foremost load Mapbox’s CSS and JS files which are hosted online on the official website:
The HTML/JS code that comes afterwards is large but don’t be intimidated, it’s quite easy to grasp. The HTML consists simply of a div identified in the JS with its id (“map”) which will receive subsequently the map.
As for the JS code, it’s required of the user (you) to have an account on Mapbox. After signing up, you should receive a token that you use to set the value of the variable “mapboxgl.accessToken”. Afterwards, we parse as a geojson the value of the Multi-Polygon we passed from the view. Note that it’s also marked as safe to avoid that the geojson code is sanitized.
In the second-to-last chunk of code inside the script tags, we’re rendering the OpenStreetMap centered around our AOI, identified by its geocoordinates. And finally we add the multi-polygon on a separate geojson layer, colored in a slightly transparent blue color:
If you go to “localhost:8000” in your browser, you should see something that looks like this:
Don’t forget to clap if this story has been useful to you.