Very new to Django (and web development in general), so apologies in advance.
I'm trying to display my Folium map in a Django webpage, but I can't seem to figure out why I end up getting a blank screen. I looked for other posts in SO, but they're all asking for either the pop-ups specifically or displaying in Jupyter.
views.py
from django.shortcuts import render, redirect, render_to_response
from django.http import HttpResponse
from django.template.loader import get_template
from django.template.context import RequestContext
import pandas as pd
import folium
def folium_map(request):
coords = [(40.7831, -73.9712), (40.6782, -73.9412), (40.7282, -73.7949)]
map = folium.Map(location=[40.7118, -74.0131], zoom_start=12)
for coord in coords:
folium.Marker(location=[coord[0], coord[1]]).add_to(map)
context = {'map': map}
return render(request, 'template.html', context)
Then, in my template.html file, I just try to insert the map in a div tag:
<div> {{ map|safe }} </div>
And it's blank. Do I need an Iframe? Is there a script source I should be running that allows for leaflet maps? How do I set it up, since I need a source? Would I have to save the map as an html file locally, because I'm trying to get this deployed so other people can use it, and if it's the case where each time the map is generated, it has to be saved locally, I'm not sure if people will appreciate having their memory or files cluttered, since this tool will be used very frequently.
Am I missing something to display the map? I'm open to other mapping libraries, but Folium is by far the easiest and most interactive I've come across.
In your code map
is a folium.Map
object, not yet a string with html/javascript. You need to render it first. Normally, this creates a single, full HTML page. For Jupyter notebooks this HTML page is put into an iframe. So there are two options:
If you don't want or need to put the map in a template, you can directly render the page: m.get_root().render()
returns a string with the full HTML/JS page.
If you want to embed the map into a template you can use an iframe:
m._repr_html_()
returns a string with an iframe with the HTML/JS page.