Saturday, July 10, 2021

Python web map with Flask/Django and Folium

 By the end of this tutorial, we will build a web app in both Flask and Django that will display at least four maps with different tile styles as seen below.


These map styles are the default styles available in the Folium package. There names are:-
  • OpenStreetMap
  • Stamen Terrain
  • Stamen Watercolor
  • Stamen Toner

You can find more tiles available in leafletjs on this web page address.




Main logic
The primary logic behind this maps is the use of folium package to generate web based leafletjs map like this:-

start_coords = (9.069, 7.472)
folium_map = folium.Map(location=start_coords, 
    zoom_start=13,
    tiles="OpenStreetMap",
    # attr='CartoDB attribution'
    max_zoom=16, 
    min_zoom=10, 
    )

folium_map.save('map.html')



Flask App

After you setup your flask app, the routes that power the maps should look like this:-

@app.route('/map1')
def index_1():
    start_coords = (9.069, 7.472)
    folium_map = folium.Map(location=start_coords, 
        zoom_start=13,
        tiles="OpenStreetMap",
        # attr='CartoDB attribution'
        max_zoom=16, 
        min_zoom=10, 
        )

    folium.Marker(
            location = start_coords,
            popup = '<h1>FATIMAH</h1>',
            tooltip = 'HEHEHE,,,,'
        ).add_to(folium_map)

    return folium_map._repr_html_()



Django Project

In the case of django, our app/views.py and html template will look like below:-

app/views.py

def map1(request):
	start_coords = (9.069, 7.472)
	folium_map = folium.Map(location=start_coords, 
        zoom_start=13,
        tiles="OpenStreetMap",
        # attr='CartoDB attribution'
        max_zoom=16, 
        min_zoom=10, 
        )

	mymap = folium_map._repr_html_() # HTML representation of the map

	context = {
		'map': mymap,
		'map_title': 'Map 1 - OpenStreetMap'
	}

	# return HttpResponse('<h1>This is map page</h1>')
	return render(request, 'map1.html', context)

html template

<div class="container">
    <div>
    	<!-- <p>This the map canvas... </p> -->
    	{{map | safe}}
    </div>


</div>

Note the part {{map | safe}} in the html, that is where the magic takes place. It displays the context folium map variable from the views.py using the safe flag.





Source Code

Download the complete code from the github page.


That is it!

No comments:

Post a Comment