mirror of
https://forge.chapril.org/tykayn/parking-land
synced 2025-06-20 01:44:42 +02:00
generate map with folium
This commit is contained in:
parent
2399302e4e
commit
8cb321a9c8
23 changed files with 115808 additions and 80 deletions
158
generate_city_map.py
Normal file
158
generate_city_map.py
Normal file
|
@ -0,0 +1,158 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
Script principal qui génère une carte d'une ville à partir de son ID OpenStreetMap
|
||||
et la convertit en image JPG en une seule commande.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import argparse
|
||||
import logging
|
||||
import importlib.util
|
||||
from datetime import datetime
|
||||
|
||||
# Configuration de la journalisation
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def check_module_available(module_name):
|
||||
"""Vérifie si un module Python est disponible."""
|
||||
return importlib.util.find_spec(module_name) is not None
|
||||
|
||||
def generate_map(osm_id, output_path=None, use_osmnx=True, verbose=False):
|
||||
"""
|
||||
Génère une carte d'une ville à partir de son ID OpenStreetMap.
|
||||
|
||||
Args:
|
||||
osm_id (int): L'identifiant OpenStreetMap de la ville
|
||||
output_path (str, optional): Chemin où sauvegarder l'image
|
||||
use_osmnx (bool): Utiliser OSMnx (True) ou Folium (False)
|
||||
verbose (bool): Afficher les messages de débogage
|
||||
|
||||
Returns:
|
||||
str: Chemin vers l'image générée ou None en cas d'erreur
|
||||
"""
|
||||
try:
|
||||
# Configurer le niveau de journalisation
|
||||
if verbose:
|
||||
logger.setLevel(logging.DEBUG)
|
||||
|
||||
# Vérifier si l'ID OSM est valide
|
||||
if osm_id <= 0:
|
||||
logger.error(f"ID OpenStreetMap invalide: {osm_id}")
|
||||
return None
|
||||
|
||||
# Déterminer quelle méthode utiliser
|
||||
osmnx_available = check_module_available('osmnx')
|
||||
|
||||
if use_osmnx and osmnx_available:
|
||||
try:
|
||||
logger.info("Utilisation d'OSMnx pour générer la carte...")
|
||||
|
||||
# Importer map.py
|
||||
import map
|
||||
|
||||
# Vérifier si la fonction config existe dans osmnx
|
||||
if not hasattr(map.ox, 'config'):
|
||||
logger.warning("La fonction 'config' n'existe pas dans OSMnx. Utilisation de Folium à la place.")
|
||||
raise AttributeError("Module 'osmnx' has no attribute 'config'")
|
||||
|
||||
# Générer la carte avec OSMnx
|
||||
city_data = map.get_city_by_osm_id(osm_id)
|
||||
|
||||
if not city_data:
|
||||
logger.warning(f"Impossible de récupérer les données pour l'ID OSM: {osm_id} avec OSMnx. Essai avec Folium...")
|
||||
raise ValueError("Aucune donnée trouvée")
|
||||
|
||||
return map.generate_city_map(city_data, output_path)
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"Erreur avec OSMnx: {str(e)}. Utilisation de Folium à la place.")
|
||||
use_osmnx = False
|
||||
|
||||
if not use_osmnx or not osmnx_available:
|
||||
if use_osmnx and not osmnx_available:
|
||||
logger.warning("OSMnx n'est pas disponible. Utilisation de Folium à la place.")
|
||||
|
||||
logger.info("Utilisation de Folium pour générer la carte...")
|
||||
|
||||
# Importer map_simple.py
|
||||
import map_simple
|
||||
|
||||
# Générer la carte avec Folium
|
||||
city_data = map_simple.get_city_data_from_osm(osm_id)
|
||||
|
||||
if not city_data:
|
||||
logger.error(f"Impossible de récupérer les données pour l'ID OSM: {osm_id}")
|
||||
return None
|
||||
|
||||
html_path = map_simple.create_folium_map(city_data, output_path)
|
||||
|
||||
if not html_path:
|
||||
logger.error("Échec de la génération de la carte HTML")
|
||||
return None
|
||||
|
||||
# Si un chemin de sortie spécifique est demandé avec une extension .jpg ou .png
|
||||
if output_path and (output_path.lower().endswith('.jpg') or output_path.lower().endswith('.png')):
|
||||
# Essayer de convertir en image
|
||||
try:
|
||||
# Importer html_to_jpg.py
|
||||
import html_to_jpg
|
||||
|
||||
# Convertir en image
|
||||
logger.info(f"Conversion de la carte HTML en {os.path.splitext(output_path)[1][1:].upper()}...")
|
||||
|
||||
# Essayer différentes méthodes de conversion
|
||||
for method in ['imgkit','wkhtmltoimage', 'cutycapt']:
|
||||
try:
|
||||
result = html_to_jpg.convert_html_to_jpg(html_path, output_path, method)
|
||||
if result:
|
||||
return result
|
||||
except Exception as e:
|
||||
logger.debug(f"Échec de la méthode {method}: {str(e)}")
|
||||
|
||||
logger.warning(f"Impossible de convertir en {os.path.splitext(output_path)[1][1:].upper()}. Utilisation du fichier HTML à la place.")
|
||||
return html_path
|
||||
|
||||
except ImportError:
|
||||
logger.warning("Module html_to_jpg non disponible. Utilisation du fichier HTML à la place.")
|
||||
return html_path
|
||||
else:
|
||||
# Si aucune conversion n'est demandée, retourner le chemin HTML
|
||||
return html_path
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Erreur lors de la génération de la carte: {str(e)}")
|
||||
return None
|
||||
|
||||
def main():
|
||||
"""
|
||||
Fonction principale qui traite les arguments de ligne de commande
|
||||
et génère la carte de la ville.
|
||||
"""
|
||||
parser = argparse.ArgumentParser(description='Génère une carte d\'une ville à partir de son ID OpenStreetMap.')
|
||||
parser.add_argument('osm_id', type=int, help='ID OpenStreetMap de la ville')
|
||||
parser.add_argument('-o', '--output', type=str, help='Chemin où sauvegarder l\'image')
|
||||
parser.add_argument('--folium', action='store_true', help='Utiliser Folium au lieu d\'OSMnx')
|
||||
parser.add_argument('-v', '--verbose', action='store_true', help='Afficher les messages de débogage')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
# Générer la carte
|
||||
output_path = generate_map(args.osm_id, args.output, not args.folium, args.verbose)
|
||||
|
||||
if output_path:
|
||||
logger.info(f"Carte générée avec succès: {output_path}")
|
||||
|
||||
# Afficher des instructions pour visualiser la carte
|
||||
if output_path.lower().endswith('.html'):
|
||||
logger.info(f"Pour visualiser la carte, ouvrez le fichier HTML dans un navigateur web:")
|
||||
logger.info(f" file://{os.path.abspath(output_path)}")
|
||||
else:
|
||||
logger.error("Échec de la génération de la carte")
|
||||
sys.exit(1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
Loading…
Add table
Add a link
Reference in a new issue