Files
PVPlant/Importer/importOSM.py
2025-03-21 01:59:33 +01:00

90 lines
3.6 KiB
Python

# ***************************************************************************
# * *
# * Copyright (c) 2016 microelly <> *
# * Copyright (c) 2020 Bernd Hahnebach <bernd@bimstatik.org> *
# * Copyright (c) 2022 Hakan Seven <hakanseven12@gmail.com> *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * This program is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
"""
Import data from OpenStreetMap
"""
import FreeCAD
import Part
from xml.etree import ElementTree as ET
import urllib.request
import urllib.parse
def import_osm_data(min_lat=40.41, min_lon=-3.71, max_lat=40.42, max_lon=-3.7):
# Configurar la consulta de Overpass API
overpass_url = "https://overpass-api.de/api/interpreter"
query = f"""
[out:xml];
(
node({min_lat},{min_lon},{max_lat},{max_lon});
way({min_lat},{min_lon},{max_lat},{max_lon});
);
out body;
>;
out skel qt;
"""
print("Descargando datos de OSM...")
response = urllib.request.urlopen(overpass_url, data=query.encode('utf-8'))
osm_data = response.read()
print("Procesando datos...")
root = ET.fromstring(osm_data)
nodes = {}
if not FreeCAD.ActiveDocument:
FreeCAD.newDocument()
doc = FreeCAD.ActiveDocument
# Creación de nodos corregida
for node in root.findall('node'):
node_id = node.attrib['id']
lat = float(node.attrib['lat'])
lon = float(node.attrib['lon'])
nodes[node_id] = FreeCAD.Vector(lon, lat, 0)
# Versión estable para todas las versiones de FreeCAD
point = Part.Vertex(nodes[node_id])
Part.show(point, f"Node_{node_id}")
# Procesar vías (manera alternativa)
for way in root.findall('way'):
way_points = [nodes[nd.attrib['ref']]
for nd in way.findall('nd')
if nd.attrib['ref'] in nodes]
if len(way_points) > 1:
try:
wire = Part.makePolygon(way_points)
Part.show(wire, f"Way_{way.attrib['id']}")
except Exception as e:
print(f"Error en vía {way.attrib['id']}: {str(e)}")
print("Importación completada!")
FreeCAD.ActiveDocument.recompute()
# Ejecutar la función
import_osm_data()