GeoDjango with Leaflet (Django-Leaflet)
This page explores the Django package "Django Leaflet". This is a helper library to simplify the use of Leaflet.js with Django. This is similar in functionality to the Folium package that
was used in the earlier GeoDjango exploration. A separate document will be developed for the direct use of Leaflet.js.
The Django-leaflet package provides 3 main areas of functionality:
- template tags to reduce the amount of boiler plate js code
- settings for defining standad common map configuration options
- widgets that can be used to create features on a map
I tried - and failed - to get this working with HTMX, although admitedly I did not spend too much time trying. Given that this package still requires some js I see limited benefit over using the leaflet.js api directly. For a "no js" solution, Folium seems to offer a better approach (with all config and setup in the backend).
Django Leaflet can be found here: https://django-leaflet.readthedocs.io/en/latest/index.html
Django-geojson can be found here: https://django-geojson.readthedocs.io/en/latest/
Guidance on displaying markers in geojson (folium) available here
Basic Use
It's pretty straightforward to create a simple map. Include the template tags and use
the leaftlet_map filter for the map itself. This saves a lot of boilderplate js defining the map although there is still need
for some js to setup the layers. In this case the |geojson tag can be used to pull in the geom data.
This is fairly simple for basic maps, although I prefer the approach taken by Folium where the map configuration is fully handled server side in Python.
# in the template load the tags
{ % load leaflet_tags % }
{ % load geojson_tags % }
{ % leaflet_js % }
{ % leaflet_css % }
# define the map with a callback to initialise
{ % leaflet_map "map" callback="map_init" % }
# javascript
function map_init(map, options) {
var country = L.geoJson(
{ { country.geom|geojsonfeature|safe } }).addTo(map);
map.fitBounds(country.getBounds());
}