Сейчас узнаем, какой подарок выпадет именно Вам
Крутите колесо
Как определить город посетителя через Яндекс API Геокодер в Tilda
Important Points, Insights, and Advantages That Showcase Our Vision and Direction
Discover the Vision Behind the Project
This abstract project focuses on developing adaptable ideas that can function across various contexts without being tied to a specific domain. We follow a flexible, thoughtful approach that adapts to each stage of the project.
Web-design
Product Animation
3D Modeling

Как определить город посетителя через Яндекс API Геокодер в Tilda

1
Создали личный кабинет разработчика, включили API Геокодера, создали для него ключ и назначили ограничение по HTTP Referer для него
Выполнили это всё по адресу https://developer.tech.yandex.ru
2
Создали любой блок и в нужном месте в тексте прописали символы трёх точек ... и назначили им ссылку #yourcity
В этом месте и подставится найденный город
3
Вставили код на страницу в блок Т123
В коде прописали значение своего API ключа
API_KEY = '3479072b-d260-443d-86a7-014a4ee38751';
Mo-ti Level Up
Видео инструкции по добавлению кода и работе с Zero Block.
Как определить город посетителя через Яндекс API Геокодер в Tilda
Фрагмент видео
Библиотека для примера
<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>
Made on
Tilda