Сейчас узнаем, какой подарок выпадет именно Вам
Крутите колесо
Как определить город посетителя через сервис DaData в Tilda
This abstract project focuses on developing adaptable ideas that can function across various contexts without being tied to a specific domain
Service #1
Visual Systems
This abstract project focuses on developing adaptable ideas.
Service #2
Visual Systems
This abstract project focuses on developing adaptable ideas.
Service #3
Illustration
This abstract project focuses on developing adaptable ideas.
Service #4
3D Modeling
This abstract project focuses on developing adaptable ideas.

Как определить город посетителя через сервис DaData в Tilda

1
Создали личный кабинет в сервисе DaData и получили там API ключ для дальнейшей работы
2
Создали любой блок и в нужном месте в тексте прописали символы трёх точек ... и назначили им ссылку #yourcity
В этом месте и подставится найденный город
3
Вставили код на страницу в блок Т123
В коде прописали значение своего API ключа
DADATA_TOKEN = '79078197e8aa6e415aa2a107163683db6b';
Mo-ti Level Up
Видео инструкции по добавлению кода и работе с Zero Block.
Как определить город посетителя через сервис DaData в Tilda
Фрагмент видео
Библиотека для примера
<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>
Made on
Tilda