Search code examples
pythoncssflaskfolium

How to center a folium map on a marker when the map is wrapped in a div


I have a folium map that is loaded into a <div>-Element with JavaScript. The <div> is smaller tha the map and i hide the rest of the map with css overflow: hidden. My problem is that the position i am focusing on the map, is in the hidden area. Is there any way to make the map focus on the point in the middle of my <div>?

Some screenshots: I made the background color gray for better visibility of the elements.

The map with the marker (not visible) Map with marker not visible

The map without overflow: hidden. The map is bigger than the containing <div> and my screen. enter image description here

What i am trying to achieve: wanted result

Code:

Requires folium and flask

app.py

import folium
from flask import Flask
from folium import Marker

app = Flask(__name__)


@app.route('/')
def index():
    return template


@app.route('/map')
def map():
    folium_map = folium.Map(location=[39.750855, -101.533079])
    Marker(location=[39.750855, -101.533079], popup='Marker').add_to(folium_map)
    return folium_map.get_root()._repr_html_()


template = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body style="background-color: rgb(128,128,128);">
    <div id="smallDiv" style="height: 40vh; width: 100%; background: aqua; overflow: hidden;"></div>
    <script>
        fetch('/map')
        .then(repsonse => repsonse.text())
        .then(data => {
            document.getElementById('smallDiv').innerHTML = data;
        })
    </script>
</body>
</html>
"""

Solution

  • You can set the height of the map to the same height as that of the div using folium.Map(height=...)