What's an alternative of Leaflet for Python w/ Flask?

from flask import Flask, render_template
import folium

app = Flask(__name__)

@app.route('/')
def index():
    # Sample elevation data (replace with your actual data)
    elevation_data = [10, 20, 30, 40, 50]

    # Create a map
    m = folium.Map(location=[51.5074, -0.1278], zoom_start=12)

    # Define a function to adjust marker color based on elevation
    def get_marker_color(elevation):
        if elevation < 20:
            return 'green'
        elif elevation < 40:
            return 'orange'
        else:
            return 'red'

    # Sample data (replace with your actual data)
    locations = [(51.5074, -0.1278), (51.5075, -0.1279), (51.5076, -0.1280), (51.5077, -0.1281), (51.5078, -0.1282)]

    # Add markers to the map with custom appearance based on elevation
    for location, elevation in zip(locations, elevation_data):
        marker_color = get_marker_color(elevation)
        folium.Marker(location=location, icon=folium.Icon(color=marker_color)).add_to(m)

    map_html = m._repr_html_()
    return render_template('index.html', map_html=map_html)

if __name__ == '__main__':
    app.run(debug=True)

index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
</head>
<body>
    <div id="map" style="width: 100%; height: 500px;"></div>
    {{ map_html | safe }}

    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
</body>
</html>

I have done this and it is still display: none;. I seems that the JS trigger is not working.


Good to know.


I have attempted to do this and it shows as if it cannot find the image even though the path is correct.

1 Like

@Sky Is this the expected result?

image

1 Like

Is that not what you wanted?

It’s close, but I can fix it to my liking.


Still not working :frowning:


Also this.

1 Like

Try this:

from flask import Flask, render_template
import folium

app = Flask(__name__)

@app.route('/')
def index():
    m = folium.Map(location=[51.5074, -0.1278], zoom_start=12)
    
    svg_icon = '<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" fill="blue" class="bi bi-circle" viewBox="0 0 16 16"><circle cx="8" cy="8" r="6"/></svg>'
    
    custom_icon = folium.CustomIcon(icon_image=svg_icon, icon_size=(40, 40))
    folium.Marker(location=[51.5074, -0.1278], icon=custom_icon).add_to(m)

    return render_template('index.html', map_html=m._repr_html_())

if __name__ == '__main__':
    app.run(debug=True)

Will test it in a bit. I will start working on what I need to do for my project.


This is still problematic. If you could help with this, that’d be great!


Anyways, thank you so much for the help! I wish I had cycles to tip you, but I don’t. :frowning:

1 Like

This should solve your error:

from flask import Flask, render_template
import folium

app = Flask(__name__)

@app.route('/')
def custom_map():
    m = folium.Map(location=[51.5074, -0.1278], zoom_start=12)
    custom_icon = folium.CustomIcon(icon_image='custom_icon.png', icon_size=(40, 40))
    popup_content = """
    <div id="custom-popup" style="display: none;">
        <h2>Custom Popup</h2>
        <p>This is a custom div element that shows up when you click the marker.</p>
    </div>
    """

    marker = folium.Marker(location=[51.5074, -0.1278], icon=custom_icon)
    marker.add_to(m)

    js_code = """
    <script>
    var marker = L.DomUtil.get("custom-popup");

    marker.addEventListener("click", function() {
        var popup = L.DomUtil.get("custom-popup");
        if (popup.style.display === "none") {
            popup.style.display = "block";
        } else {
            popup.style.display = "none";
        }
    });
    </script>
    """

    m.get_root().html.add_child(folium.Element(js_code)) # add the js code to the map.
    map_html = m._repr_html_()
    return render_template('custom_map.html', map_html=map_html)

if __name__ == '__main__':
    app.run(debug=True)

It’s fine, I appreciate that but it’s okay!

EDIT: @Sky It never actually uses popup-content It does not do anything upon click currently.

1 Like

Try that code first, then let me know.

So it didn’t work or did it.

@Sky It did not work. Sorry for the confusion.

No luck. It says there is no such file or directory.

1 Like

Could you please share your Repl with me if possible? This would be a preferable approach compared to only sending code snippets, among other options.

@Sky WorldCache
In the search bar, put “GCA9932”.

1 Like

try this:

@app.route("/cache/<cacheWP>")
def cache(cacheWP):
    cache = geocaching.get_cache(wp=cacheWP)

    # Get logs
    def to_dict(log):
        return {
            name: str(getattr(log, name, 'null'))
            for name in 'author text type uuid visited'.split()
        }

    logs = [to_dict(log) for log in cache.load_logbook()]

    # Create a map
    m = folium.Map(location=cache.location, zoom_start=12)

    # Define a custom icon
    custom_icon = folium.CustomIcon(icon_image='./static/imgs/type_traditional.svg', icon_size=(20, 20))
    
    # Add the marker with the custom icon
    marker = folium.Marker(location=cache.location, icon=custom_icon)
    marker.add_to(m)

    # JavaScript code for showing/hiding the popup
    js_code = """
    <script>
    var marker = L.DomUtil.get("custom-popup");

    marker.addEventListener("click", function() {
        var popup = L.DomUtil.get("custom-popup");
        if (popup.style.display === "none") {
            popup.style.display = "block";
        } else {
            popup.style.display = "none";
        }
    });
    </script>
    """

    # Add the JavaScript code to the map
    m.get_root().html.add_child(folium.Element(js_code))
    
    # Define the popup content
    popup_content = """
    <div id="custom-popup" style="display: none;">
        <h2>{}</h2>
        <p>{}</p>
    </div>
    """.format(cache.name, cache.description)

    map_html = m._repr_html_()
    
    return render_template("cache.html", cacheName=cache.name, cacheWP=cache.wp, cacheAuthor=cache.author,
                           cacheDescription=cache.description, cacheTerrain=cache.terrain,
                           cacheDifficulty=cache.difficulty, cacheType=str(cache.type).split(".")[1],
                           cacheSize=str(cache.size).split(".")[1].capitalize(), logs=logs,
                           logCount=len(logs), map_html=map_html, popup_content=popup_content)

@Sky No luck :frowning:
I wonder why it isn’t working – I mean it certainly seems like it should.

1 Like

Hmm, it should be fine. I mean, it worked for me, so I’m not entirely sure, and I apologize :(.

image

@Sky No click reaction :frowning:
What do you think it is?

BTW Here’s a screen recording.

1 Like

Do you have any idea on how to fix it?
I’ve tried a few thing but not of them work :frowning: @Sky

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.