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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
)
|
| 45 |
-
show_zoom_ctrl = gr.Checkbox(True, label="Show zoom control")
|
| 46 |
-
show_scale = gr.Checkbox(True, label="Show scale bar")
|
| 47 |
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
|
| 51 |
-
# IMPORTANT: allow scripts so Leaflet can run
|
| 52 |
-
out = gr.HTML(label="Map", sanitize=False)
|
| 53 |
|
| 54 |
-
demo.load(render_map, [lat, lon, zoom, geojson_file, show_zoom_ctrl, show_scale, tileset], out)
|
| 55 |
-
btn.click(render_map, [lat, lon, zoom, geojson_file, show_zoom_ctrl, show_scale, tileset], out)
|
| 56 |
|
| 57 |
if __name__ == "__main__":
|
|
|
|
| 58 |
demo.launch()
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import json
|
| 3 |
+
import uuid
|
| 4 |
+
import html
|
| 5 |
+
from typing import Optional
|
| 6 |
|
| 7 |
+
# Default center (Palermo, IT)
|
| 8 |
+
DEFAULT_CENTER = (38.1157, 13.3615)
|
| 9 |
DEFAULT_ZOOM = 12
|
| 10 |
|
| 11 |
+
LEAFLET_CSS = "https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
|
| 12 |
+
LEAFLET_JS = "https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"
|
| 13 |
+
LEAFLET_DRAW_CSS = "https://unpkg.com/leaflet-draw@1.0.4/dist/leaflet.draw.css"
|
| 14 |
+
LEAFLET_DRAW_JS = "https://unpkg.com/leaflet-draw@1.0.4/dist/leaflet.draw.js"
|
| 15 |
+
|
| 16 |
+
TILES_URL = "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
|
| 17 |
+
ATTRIB = "© <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# ---------- Helpers ----------
|
| 21 |
+
def _safe_parse_geojson(geojson_text: Optional[str]):
|
| 22 |
+
if not geojson_text:
|
| 23 |
+
return None, None
|
| 24 |
+
try:
|
| 25 |
+
data = json.loads(geojson_text)
|
| 26 |
+
if not isinstance(data, dict):
|
| 27 |
+
raise ValueError("GeoJSON must be a JSON object")
|
| 28 |
+
return data, None
|
| 29 |
+
except Exception as e:
|
| 30 |
+
return None, f"Invalid GeoJSON: {e}"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _escape_for_srcdoc(s: str) -> str:
|
| 34 |
+
"""Escape HTML for safe embedding into an iframe srcdoc attribute."""
|
| 35 |
+
return html.escape(s, quote=True)
|
| 36 |
+
|
| 37 |
|
| 38 |
+
def _read_file_bytes(uploaded: Optional[object]) -> Optional[str]:
|
| 39 |
+
"""Read gr.File input (bytes, file-like, or dict with 'bytes')."""
|
| 40 |
+
if uploaded is None:
|
| 41 |
+
return None
|
| 42 |
+
if isinstance(uploaded, (bytes, bytearray)):
|
| 43 |
+
data = bytes(uploaded)
|
| 44 |
+
elif hasattr(uploaded, "read"):
|
| 45 |
+
data = uploaded.read()
|
| 46 |
+
elif isinstance(uploaded, dict) and "bytes" in uploaded:
|
| 47 |
+
data = uploaded["bytes"]
|
| 48 |
+
else:
|
| 49 |
+
return None
|
| 50 |
+
for enc in ("utf-8", "utf-8-sig", "cp1252", "latin-1"):
|
| 51 |
try:
|
| 52 |
+
return data.decode(enc)
|
| 53 |
+
except Exception:
|
| 54 |
+
continue
|
| 55 |
+
return None
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# ---------- Leaflet HTML ----------
|
| 59 |
+
def build_leaflet_html(
|
| 60 |
+
geojson_text: Optional[str],
|
| 61 |
+
lat: float,
|
| 62 |
+
lng: float,
|
| 63 |
+
zoom: int,
|
| 64 |
+
height_px: int = 640,
|
| 65 |
+
) -> str:
|
| 66 |
+
"""Return an HTML *document* string with a Leaflet map and optional GeoJSON overlay, wrapped in an iframe."""
|
| 67 |
+
map_id = f"map_{uuid.uuid4().hex}"
|
| 68 |
+
|
| 69 |
+
# Validate/parse GeoJSON (optional)
|
| 70 |
+
gj_data, gj_err = _safe_parse_geojson(geojson_text)
|
| 71 |
+
gj_json_str = json.dumps(gj_data) if gj_data is not None else "null"
|
| 72 |
+
|
| 73 |
+
note = ""
|
| 74 |
+
if gj_err:
|
| 75 |
+
note = (
|
| 76 |
+
f"<div style='padding:10px; background:#fff3cd; border:1px solid #ffe69c; color:#664d03; margin-bottom:8px;'>"
|
| 77 |
+
f"{html.escape(gj_err)}</div>"
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
# IMPORTANT: use doubled braces {{ }} around literal JS/CSS braces
|
| 81 |
+
inner_html = f"""
|
| 82 |
+
<!DOCTYPE html>
|
| 83 |
+
<html>
|
| 84 |
+
<head>
|
| 85 |
+
<meta charset="utf-8" />
|
| 86 |
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
| 87 |
+
<link rel="stylesheet" href="{LEAFLET_CSS}"/>
|
| 88 |
+
<link rel="stylesheet" href="{LEAFLET_DRAW_CSS}"/>
|
| 89 |
+
<style>
|
| 90 |
+
html, body {{ margin:0; padding:0; height:100%; }}
|
| 91 |
+
#{map_id} {{ height: 100%; width: 100%; }}
|
| 92 |
+
.leaflet-container {{ font: 12px/1.5 system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, Arial, "Apple Color Emoji", "Segoe UI Emoji"; }}
|
| 93 |
+
.wrap {{ display:flex; flex-direction:column; height:100%; }}
|
| 94 |
+
.note {{ flex: none; }}
|
| 95 |
+
.mapwrap {{ flex: 1 1 auto; min-height:0; }}
|
| 96 |
+
</style>
|
| 97 |
+
</head>
|
| 98 |
+
<body>
|
| 99 |
+
<div class="wrap">
|
| 100 |
+
<div class="note">{note}</div>
|
| 101 |
+
<div class="mapwrap"><div id="{map_id}"></div></div>
|
| 102 |
+
</div>
|
| 103 |
+
|
| 104 |
+
<script src="{LEAFLET_JS}"></script>
|
| 105 |
+
<script src="{LEAFLET_DRAW_JS}"></script>
|
| 106 |
+
<script>
|
| 107 |
+
const map = L.map('{map_id}').setView([{lat}, {lng}], {zoom});
|
| 108 |
+
|
| 109 |
+
L.tileLayer('{TILES_URL}', {{
|
| 110 |
+
maxZoom: 19,
|
| 111 |
+
attribution: '{ATTRIB}'
|
| 112 |
+
}}).addTo(map);
|
| 113 |
+
|
| 114 |
+
L.control.scale().addTo(map);
|
| 115 |
+
|
| 116 |
+
const drawnItems = new L.FeatureGroup();
|
| 117 |
+
map.addLayer(drawnItems);
|
| 118 |
+
const drawControl = new L.Control.Draw({{
|
| 119 |
+
draw: {{ polygon: true, polyline: true, rectangle: true, circle: false, marker: true, circlemarker: false }},
|
| 120 |
+
edit: {{ featureGroup: drawnItems }}
|
| 121 |
+
}});
|
| 122 |
+
map.addControl(drawControl);
|
| 123 |
+
map.on(L.Draw.Event.CREATED, function (e) {{ drawnItems.addLayer(e.layer); }});
|
| 124 |
+
|
| 125 |
+
const providedGeoJSON = {gj_json_str};
|
| 126 |
+
if (providedGeoJSON) {{
|
| 127 |
+
const gjLayer = L.geoJSON(providedGeoJSON, {{
|
| 128 |
+
style: function() {{ return {{ weight: 2 }}; }},
|
| 129 |
+
onEachFeature: function (feature, layer) {{
|
| 130 |
+
const props = feature && feature.properties ? feature.properties : {{}};
|
| 131 |
+
const content = `<pre style="margin:0;">${{JSON.stringify(props, null, 2)}}</pre>`;
|
| 132 |
+
layer.bindPopup(content);
|
| 133 |
+
}}
|
| 134 |
+
}}).addTo(map);
|
| 135 |
+
try {{
|
| 136 |
+
const b = gjLayer.getBounds();
|
| 137 |
+
if (b && b.isValid()) map.fitBounds(b, {{ padding: [20, 20] }});
|
| 138 |
+
}} catch (err) {{ /* ignore */ }}
|
| 139 |
+
}}
|
| 140 |
+
</script>
|
| 141 |
+
</body>
|
| 142 |
+
</html>
|
| 143 |
+
"""
|
| 144 |
+
|
| 145 |
+
srcdoc = _escape_for_srcdoc(inner_html)
|
| 146 |
+
return (
|
| 147 |
+
f"<iframe style='width:100%; height:{height_px}px; border:0; border-radius:8px' "
|
| 148 |
+
f"sandbox='allow-scripts allow-same-origin' referrerpolicy='no-referrer' "
|
| 149 |
+
f"srcdoc='{srcdoc}'></iframe>"
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
# ---------- Gradio callbacks ----------
|
| 154 |
+
def run_show(
|
| 155 |
+
uploaded_file: Optional[object],
|
| 156 |
+
geojson_text: str,
|
| 157 |
+
lat: float,
|
| 158 |
+
lng: float,
|
| 159 |
+
zoom: int,
|
| 160 |
+
height_px: int,
|
| 161 |
+
):
|
| 162 |
+
# Priority: file > text (robust handling)
|
| 163 |
+
gj_text = _read_file_bytes(uploaded_file)
|
| 164 |
+
if gj_text is None and geojson_text and geojson_text.strip():
|
| 165 |
+
gj_text = geojson_text
|
| 166 |
+
|
| 167 |
+
html_value = build_leaflet_html(gj_text, float(lat), float(lng), int(zoom), height_px=int(height_px))
|
| 168 |
+
return html_value
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def demo_app():
|
| 172 |
+
with gr.Blocks(title="Leaflet + OpenStreetMap (Gradio)", fill_height=True) as demo:
|
| 173 |
+
# Sidebar = "page outline"
|
| 174 |
+
with gr.Sidebar():
|
| 175 |
+
gr.Markdown("## 🧭 Outline")
|
| 176 |
+
gr.Markdown(
|
| 177 |
+
"- **Overview**\n"
|
| 178 |
+
"- **Controls**\n"
|
| 179 |
+
"- **Data Input**\n"
|
| 180 |
+
"- **Help & Tips**"
|
| 181 |
+
)
|
| 182 |
+
gr.Markdown("### Help & Tips")
|
| 183 |
+
gr.Markdown(
|
| 184 |
+
"- Upload a `.geojson` or paste JSON.\n"
|
| 185 |
+
"- Use the draw tools to sketch.\n"
|
| 186 |
+
"- Click features to see properties."
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
# Main content
|
| 190 |
+
gr.Markdown("# 🗺️ Leaflet + OpenStreetMap")
|
| 191 |
+
gr.Markdown(
|
| 192 |
+
"Shows OpenStreetMap tiles with Leaflet inside a Gradio app. "
|
| 193 |
+
"Optionally overlay a GeoJSON file or pasted text. Includes basic draw tools (no backend needed)."
|
| 194 |
)
|
|
|
|
|
|
|
| 195 |
|
| 196 |
+
with gr.Row():
|
| 197 |
+
with gr.Column(scale=1):
|
| 198 |
+
gr.Markdown("## Controls")
|
| 199 |
+
lat_in = gr.Number(value=DEFAULT_CENTER[0], label="Center latitude", precision=6)
|
| 200 |
+
lng_in = gr.Number(value=DEFAULT_CENTER[1], label="Center longitude", precision=6)
|
| 201 |
+
zoom_in = gr.Slider(3, 19, value=DEFAULT_ZOOM, step=1, label="Zoom")
|
| 202 |
+
height_in = gr.Slider(360, 1200, value=640, step=10, label="Map height (px)")
|
| 203 |
+
|
| 204 |
+
gr.Markdown("## Data Input")
|
| 205 |
+
file_in = gr.File(
|
| 206 |
+
label="Upload GeoJSON (.geojson or .json)",
|
| 207 |
+
file_types=[".geojson", ".json"],
|
| 208 |
+
type="binary",
|
| 209 |
+
)
|
| 210 |
+
text_in = gr.Textbox(
|
| 211 |
+
label="Or paste GeoJSON",
|
| 212 |
+
lines=8,
|
| 213 |
+
placeholder='{"type": "FeatureCollection", "features": []}',
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
with gr.Row():
|
| 217 |
+
show_btn = gr.Button("Show / Refresh", variant="primary")
|
| 218 |
+
clear_btn = gr.Button("Clear overlays")
|
| 219 |
+
|
| 220 |
+
with gr.Column(scale=2):
|
| 221 |
+
gr.Markdown("## Map")
|
| 222 |
+
map_html = gr.HTML(label="Map", show_label=False)
|
| 223 |
+
|
| 224 |
+
# Wire up actions
|
| 225 |
+
show_btn.click(
|
| 226 |
+
fn=run_show,
|
| 227 |
+
inputs=[file_in, text_in, lat_in, lng_in, zoom_in, height_in],
|
| 228 |
+
outputs=[map_html],
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
def _clear():
|
| 232 |
+
return build_leaflet_html(None, DEFAULT_CENTER[0], DEFAULT_CENTER[1], DEFAULT_ZOOM, height_px=640)
|
| 233 |
+
|
| 234 |
+
clear_btn.click(fn=_clear, inputs=[], outputs=[map_html])
|
| 235 |
+
|
| 236 |
+
# Initial render
|
| 237 |
+
map_html.value = build_leaflet_html(None, DEFAULT_CENTER[0], DEFAULT_CENTER[1], DEFAULT_ZOOM, height_px=640)
|
| 238 |
|
| 239 |
+
return demo
|
|
|
|
|
|
|
| 240 |
|
|
|
|
|
|
|
| 241 |
|
| 242 |
if __name__ == "__main__":
|
| 243 |
+
demo = demo_app()
|
| 244 |
demo.launch()
|