<script>
const DADATA_TOKEN = '79078197e8aa6e415aa2a107163683db6b';
const CACHE_ENABLED = true;
const CACHE_HOURS = 24;
const NOCITY_TEXT = 'Ваш город';
const GEO_TIMEOUT = 10000;
function extractCity(suggestion) {
if (!suggestion || !suggestion.data) return null;
// city — для городов, settlement — для посёлков, region — если город совпадает с регионом
return suggestion.data.city || suggestion.data.settlement || suggestion.data.region || null;
}
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 getCityFromDadata(lat, lon) {
const url = 'https://suggestions.dadata.ru/suggestions/api/4_1/rs/geolocate/address';
const options = {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Token ' + DADATA_TOKEN
},
body: JSON.stringify({ lat: lat, lon: lon })
};
return fetch(url, options)
.then(response => {
if (!response.ok) throw new Error('HTTP ' + response.status);
return response.json();
})
.then(data => {
if (!data.suggestions || data.suggestions.length === 0) {
throw new Error('Нет результатов от Dadata');
}
return extractCity(data.suggestions[0]);
});
}
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;
getCityFromDadata(lat, lon)
.then(city => {
setCachedCity(city);
displayCity(city);
})
.catch(error => {
console.error('Ошибка Dadata:', error);
displayCity(null);
});
},
function(error) {
console.error('Геолокация отклонена:', error.message);
displayCity(null);
},
{
enableHighAccuracy: true,
timeout: GEO_TIMEOUT,
maximumAge: 0
}
);
} else {
console.log('Geolocation API не поддерживается');
displayCity(null);
}
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
</script>
<style>
a[href="#yourcity"] {
pointer-events: none;
}
</style>