Загрузка данных
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<title>Геолокация (freeCodeCamp проект)</title>
<!-- 1. Обязательно подключаем стили Leaflet -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
h1 { margin-bottom: 10px; }
#btn { padding: 10px 20px; font-size: 16px; cursor: pointer; }
#info { margin: 15px 0; padding: 10px; background: #f5f5f5; border-radius: 4px; min-height: 1.2em; }
/* 2. Карта должна иметь высоту, иначе будет белой */
#map { height: 500px; width: 100%; border: 1px solid #ccc; box-sizing: border-box; }
</style>
</head>
<body>
<h1>Геолокация по IP (проект freeCodeCamp)</h1>
<button id="btn">Определить местоположение</button>
<p id="info">Нажми кнопку, чтобы начать</p>
<div id="map"></div>
<!-- 3. Подключаем JS Leaflet -->
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
// Сюда вставляй ключ ТОЛЬКО когда будешь готов
const API_KEY = '';
const btn = document.getElementById('btn');
const info = document.getElementById('info');
let map;
btn.addEventListener('click', async () => {
btn.disabled = true;
info.textContent = 'Запрос к API...';
// Сначала ставим тестовую точку (Москва), чтобы карта точно появилась
const testLat = 55.7558;
const testLng = 37.6176;
const testCountry = 'Russia';
const testCity = 'Moscow';
if (!map) {
map = L.map('map').setView([testLat, testLng], 6);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
}
// Удаляем старые маркеры
map.eachLayer(layer => {
if (layer instanceof L.Marker) map.removeLayer(layer);
});
try {
// Если ключа нет, сразу показываем тестовые данные и не делаем запрос
if (!API_KEY) {
info.textContent = `Тестовые данные (ключ не вставлен): Страна: ${testCountry}, Город: ${testCity}`;
L.marker([testLat, testLng])
.addTo(map)
.bindPopup(`<b>${testCity}, ${testCountry}</b>`)
.openPopup();
return;
}
const res = await fetch(`https://geo.ipify.org/api/v2/location?apiKey=${API_KEY}`);
if (!res.ok) {
const errorData = await res.json().catch(() => ({}));
const msg = errorData.message ? `${res.status} ${errorData.message}` : res.status.toString();
info.textContent = `Ошибка API: ${msg}. Пока показываем тестовые данные.`;
// Показываем тестовую точку даже при ошибке API
L.marker([testLat, testLng])
.addTo(map)
.bindPopup(`<b>${testCity}, ${testCountry}</b>`)
.openPopup();
throw new Error(`HTTP ${res.status}`);
}
const data = await res.json();
const { country, city, latitude, longitude } = data;
info.textContent = `Страна: ${country}, Город: ${city}`;
map.setView([latitude, longitude], 6);
L.marker([latitude, longitude])
.addTo(map)
.bindPopup(`<b>${city}, ${country}</b>`)
.openPopup();
} catch (err) {
console.error(err);
info.textContent = 'Произошла ошибка: ' + err.message;
} finally {
btn.disabled = false;
}
});
</script>
</body>
</html>