File size: 5,996 Bytes
097a6f2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
# lugar_3.py
# Gradio 6.2.0
# Layout FULL PAGE (sem margens laterais)
# ✔ Busca por nome e coordenadas
# ✔ Mapa Leaflet
# ✔ Google Street View (fallback automático)
# ✔ Apple Maps
import re
import html
import requests
import gradio as gr
# ----------------------------
# Parsing / Geocoding
# ----------------------------
_COORD_RE = re.compile(
r"""
^\s*
(?:lat\s*[:=]?\s*)?(-?\d+(?:\.\d+)?)
(?:\s*[,;]\s*|\s+)
(?:lon|lng|long)?\s*[:=]?\s*(-?\d+(?:\.\d+)?)
\s*$
""",
re.IGNORECASE | re.VERBOSE
)
def parse_coords(text: str):
if not text:
return None
m = _COORD_RE.match(text.strip())
if not m:
return None
lat = float(m.group(1))
lon = float(m.group(2))
if not (-90 <= lat <= 90 and -180 <= lon <= 180):
raise ValueError("Coordenadas fora do intervalo válido.")
return lat, lon
def geocode_by_name(query: str):
url = "https://nominatim.openstreetmap.org/search"
params = {"q": query, "format": "jsonv2", "limit": 1}
headers = {"User-Agent": "GradioMapFullPage"}
r = requests.get(url, params=params, headers=headers, timeout=20)
r.raise_for_status()
data = r.json()
if not data:
raise ValueError(f"Local não encontrado: {query}")
lat = float(data[0]["lat"])
lon = float(data[0]["lon"])
name = data[0].get("display_name", query)
return lat, lon, name
def resolve_location(mode, place, lat, lon):
if mode == "coords":
return float(lat), float(lon), f"{lat:.6f}, {lon:.6f}"
if mode == "auto":
parsed = parse_coords(place)
if parsed:
la, lo = parsed
return la, lo, f"{la:.6f}, {lo:.6f}"
return geocode_by_name(place)
# ----------------------------
# Map HTML (srcdoc)
# ----------------------------
def build_srcdoc(lat, lon, zoom, basemap, title):
sv0 = f"https://www.google.com/maps/@?api=1&map_action=pano&viewpoint={lat:.7f},{lon:.7f}"
a0 = f"https://maps.apple.com/place?coordinate={lat:.7f},{lon:.7f}"
doc = f"""
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<style>
html, body {{
margin:0;
padding:0;
width:100%;
}}
.wrap {{
width:100%;
padding:12px;
}}
#map {{
width:100%;
height:70vh;
border-radius:14px;
border:1px solid #e5e7eb;
}}
.panel {{
margin-top:10px;
padding:12px;
border:1px solid #e5e7eb;
border-radius:14px;
}}
.btns {{
display:flex;
gap:10px;
margin-top:8px;
}}
.btn {{
padding:10px 14px;
border-radius:10px;
font-weight:700;
text-decoration:none;
color:white;
}}
.btn.google {{ background:#1a73e8; }}
.btn.apple {{ background:#000; }}
code {{
background:#f3f4f6;
padding:3px 8px;
border-radius:8px;
}}
</style>
</head>
<body>
<div class="wrap">
<h3>{html.escape(title)}</h3>
<div id="map"></div>
<div class="panel">
<div><b>Coordenadas:</b> <code id="coords">{lat:.7f}, {lon:.7f}</code></div>
<div class="btns">
<a id="streetLink" class="btn google" href="{sv0}" target="_blank">Google Street View</a>
<a id="appleLink" class="btn apple" href="{a0}" target="_blank">Apple Maps</a>
</div>
</div>
</div>
<script>
const map = L.map('map').setView([{lat:.7f}, {lon:.7f}], {zoom});
const bases = {{
"OSM": L.tileLayer('https://{{s}}.tile.openstreetmap.org/{{z}}/{{x}}/{{y}}.png'),
"Esri Satellite": L.tileLayer(
'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{{z}}/{{y}}/{{x}}')
}};
(bases["{basemap}"] || bases["OSM"]).addTo(map);
L.control.layers(bases).addTo(map);
let marker = L.marker([{lat:.7f}, {lon:.7f}]).addTo(map);
function update(lat, lon) {{
marker.setLatLng([lat, lon]);
document.getElementById("coords").textContent =
lat.toFixed(7) + ", " + lon.toFixed(7);
document.getElementById("streetLink").href =
"https://www.google.com/maps/@?api=1&map_action=pano&viewpoint=" + lat + "," + lon;
document.getElementById("appleLink").href =
"https://maps.apple.com/place?coordinate=" + lat + "," + lon;
}}
map.on("click", e => update(e.latlng.lat, e.latlng.lng));
</script>
</body>
</html>
"""
return html.escape(doc, quote=True)
def run(mode, place, lat, lon, zoom, basemap):
lat0, lon0, name = resolve_location(mode, place, lat, lon)
srcdoc = build_srcdoc(lat0, lon0, zoom, basemap, f"📍 {name}")
iframe = f'<iframe style="width:100vw; height:85vh; border:0;" srcdoc="{srcdoc}"></iframe>'
return f"OK — {name}", iframe
# ----------------------------
# UI (FULL PAGE)
# ----------------------------
CSS = """
.gradio-container {
max-width: 100% !important;
padding-left: 0 !important;
padding-right: 0 !important;
}
"""
with gr.Blocks(css=CSS, title="Mapa Full Page") as demo:
with gr.Row():
mode = gr.Radio(["auto", "nome", "coords"], value="auto", label="Modo")
place = gr.Textbox(label="Local ou coordenadas", value="Lisboa")
lat_in = gr.Number(label="Latitude", value=38.7223, precision=7)
lon_in = gr.Number(label="Longitude", value=-9.1393, precision=7)
basemap = gr.Dropdown(["Esri Satellite", "OSM"], value="Esri Satellite", label="Base map")
zoom = gr.Slider(3, 20, value=16, label="Zoom")
btn = gr.Button("Mostrar", variant="primary")
status = gr.Textbox(label="Status", interactive=False)
view = gr.HTML()
btn.click(run, [mode, place, lat_in, lon_in, zoom, basemap], [status, view])
demo.load(lambda: run("auto", "Lisboa", 38.7223, -9.1393, 12, "Esri Satellite"), outputs=[status, view])
demo.launch()
|