<script>
const API_KEY = '3479072b-d260-443d-86a7-014a4ee38751';
const CACHE_ENABLED = true;
const CACHE_HOURS = 24;
const NOCITY_TEXT = 'Ваш город';
function extractCity(geoObject) {
const meta = geoObject.metaDataProperty.GeocoderMetaData;
if (meta.Address && meta.Address.Components) {
const locality = meta.Address.Components.find(c => c.kind === 'locality');
if (locality) return locality.name;
}
const parts = meta.text.split(', ');
return parts[1] || meta.text;
}
function getCachedCity() {
if (!CACHE_ENABLED) return null;
try {
const cached = localStorage.getItem('userCity');
if (!cached) return null;
const data = JSON.parse(cached);
const now = Date.now();
const maxAge = CACHE_HOURS * 60 * 60 * 1000;
if (now - data.timestamp < maxAge) {
console.log('Город из кеша:', data.city);
return data.city;
}
localStorage.removeItem('userCity');
} catch (e) {
localStorage.removeItem('userCity');
}
return null;
}
function setCachedCity(city) {
if (!CACHE_ENABLED) return;
try {
localStorage.setItem('userCity', JSON.stringify({
city: city,
timestamp: Date.now()
}));
} catch (e) {}
}
function displayCity(city) {
const text = city || NOCITY_TEXT;
document.querySelectorAll('a[href="#yourcity"]').forEach(el => {
el.textContent = text;
});
}
function getCityFromCoordinates(lat, lon) {
const url = `https://geocode-maps.yandex.ru/v1/?apikey=${API_KEY}&geocode=${lon},${lat}&format=json`;
return fetch(url)
.then(response => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
})
.then(data => {
const geoObject = data.response.GeoObjectCollection.featureMember[0].GeoObject;
return extractCity(geoObject);
});
}
function getCityByIP() {
const url = `https://geocode-maps.yandex.ru/v1/?apikey=${API_KEY}&geocode=me&format=json`;
return fetch(url)
.then(response => response.json())
.then(data => {
const geoObject = data.response.GeoObjectCollection.featureMember[0].GeoObject;
return extractCity(geoObject);
});
}
function init() {
const cached = getCachedCity();
if (cached) {
displayCity(cached);
return;
}
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(
function(position) {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
getCityFromCoordinates(lat, lon)
.then(city => {
setCachedCity(city);
displayCity(city);
})
.catch(error => {
console.error('Ошибка геокодирования:', error);
getCityByIP()
.then(city => {
setCachedCity(city);
displayCity(city);
})
.catch(() => displayCity(null));
});
},
function(error) {
console.error('Геолокация отклонена:', error.message);
getCityByIP()
.then(city => {
setCachedCity(city);
displayCity(city);
})
.catch(() => displayCity(null));
},
{
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
}
);
} else {
console.log('Geolocation API не поддерживается');
getCityByIP()
.then(city => {
setCachedCity(city);
displayCity(city);
})
.catch(() => displayCity(null));
}
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
</script>
<style>
a[href="#yourcity"]{
pointer-events: none;
}
</style>