Files
map_yandex/main.py
2025-09-23 20:13:51 +05:00

159 lines
6.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Интерактивная карта образовательных учреждений Челябинска
Отображает 72+ учебных заведения: университеты, институты, колледжи, техникумы, лицеи и училища
Использует Yandex Maps API для создания интерактивной карты с фильтрацией
"""
import json
import os
import webbrowser
from pathlib import Path
from jinja2 import Template
def load_colleges_data():
"""Загружает данные об образовательных учреждениях из JSON файла"""
current_dir = Path(__file__).parent
colleges_file = current_dir / "colleges_data.json"
try:
with open(colleges_file, 'r', encoding='utf-8') as f:
return json.load(f)
except FileNotFoundError:
print(f"Файл с данными об образовательных учреждениях не найден: {colleges_file}")
return []
except json.JSONDecodeError as e:
print(f"Ошибка при чтении JSON файла: {e}")
return []
def generate_map_html(colleges_data, api_key=""):
"""Генерирует HTML файл с интерактивной картой образовательных учреждений"""
current_dir = Path(__file__).parent
template_file = current_dir / "map_template.html"
try:
with open(template_file, 'r', encoding='utf-8') as f:
template_content = f.read()
except FileNotFoundError:
print(f"Шаблон HTML не найден: {template_file}")
return None
# Заменяем placeholder API ключа
template_content = template_content.replace("YOUR_API_KEY", api_key)
# Создаем шаблон Jinja2
template = Template(template_content)
# Рендерим HTML с данными о колледжах
html_content = template.render(
colleges=colleges_data,
colleges_json=json.dumps(colleges_data, ensure_ascii=False)
)
# Сохраняем HTML файл
output_file = current_dir / "chelyabinsk_colleges_map.html"
with open(output_file, 'w', encoding='utf-8') as f:
f.write(html_content)
return output_file
def print_colleges_info(colleges_data):
"""Выводит информацию об образовательных учреждениях в консоль"""
print("=" * 80)
print("ОБРАЗОВАТЕЛЬНЫЕ УЧРЕЖДЕНИЯ ЧЕЛЯБИНСКА")
print("=" * 80)
# Группировка по типам
types_stats = {}
for institution in colleges_data:
inst_type = institution.get('type', 'Неопределенный')
types_stats[inst_type] = types_stats.get(inst_type, 0) + 1
print(f"\n📊 Статистика по типам учреждений:")
for inst_type, count in sorted(types_stats.items()):
print(f" {inst_type}: {count}")
print(f"\n🎯 Всего учреждений: {len(colleges_data)}")
for i, institution in enumerate(colleges_data, 1):
print(f"\n{i}. {institution['name']}")
print(f" Тип: {institution.get('type', 'Не указан')}")
print(f" Адрес: {institution['address']}")
coords = institution.get('coordinates', {})
if coords:
print(f" Координаты: {coords.get('lat', 'Н')}, {coords.get('lon', 'Н')}")
specialties = institution.get('specialties', [])
if specialties:
print(f" Специальности: {', '.join(specialties)}")
contacts = institution.get('contacts', {})
if contacts.get('website'):
print(f" Веб-сайт: {contacts['website']}")
if contacts.get('phone'):
print(f" Телефон: {contacts['phone']}")
print(f" Описание: {institution.get('description', 'Не указано')}")
print("-" * 80)
def main():
"""Основная функция программы"""
print("Генерация карты колледжей Челябинска...")
# Загружаем данные о колледжах
colleges_data = load_colleges_data()
if not colleges_data:
print("Не удалось загрузить данные о колледжах!")
return
print(f"Загружено {len(colleges_data)} колледжей")
# Выводим информацию о колледжах
print_colleges_info(colleges_data)
# Запрашиваем API ключ у пользователя
print("\n" + "=" * 80)
print("НАСТРОЙКА API КЛЮЧА YANDEX MAPS")
print("=" * 80)
print("Для работы карты необходим API ключ Yandex Maps.")
print("Получить ключ можно на: https://developer.tech.yandex.ru/")
print("Если у вас нет ключа, оставьте поле пустым (карта будет работать с ограничениями)")
api_key = input("\nВведите ваш API ключ Yandex Maps (или нажмите Enter для пропуска): ").strip()
# Генерируем HTML файл с картой
output_file = generate_map_html(colleges_data, api_key)
if output_file:
print(f"\n✅ Карта успешно создана: {output_file}")
# Предлагаем открыть карту в браузере
open_browser = input("\nОткрыть карту в браузере? (y/N): ").strip().lower()
if open_browser in ['y', 'yes', 'да', 'д']:
try:
webbrowser.open(f'file://{output_file.absolute()}')
print("Карта открыта в браузере!")
except Exception as e:
print(f"Не удалось открыть браузер: {e}")
print(f"Откройте файл вручную: {output_file.absolute()}")
else:
print(f"Откройте файл в браузере: {output_file.absolute()}")
print("\n📍 На карте отмечены следующие колледжи:")
for college in colleges_data:
print(f"{college['name']}")
else:
print("❌ Ошибка при создании карты!")
if __name__ == "__main__":
main()