@Nubbb

Как определить город по ip пользователя через google в Laravel + Nuxt?

подскажите, как организовать определение местоположения пользователя на сайте, то есть перед загрузкой сайта, определить местоположение

думал сделать через плагин, но координаты отображает уже после загрузки сайта, а нужно до показа страницы

export default function (context) {
  navigator.geolocation.getCurrentPosition(
    (position) => {
      console.log(position.coords.latitude)
      console.log(position.coords.longitude)
    },
    (error) => {
      console.log(error.message)
    }
  )
}


может есть какой пакет для Laravel, который определяет город пользователя по ip пользователя? если например отправить запрос на Laravel через axios

чтобы с бэка приходили координаты пользователя: и город, координаты и я их записал в стор

export default async function (context) {
  await context.$axios
    .get('api/v1/geo')
    .then((response) =>
      context.store.commit('user/SET_GEO', response.geo)
    )
}
  • Вопрос задан
  • 452 просмотра
Пригласить эксперта
Ответы на вопрос 2
@Kostik_1993
Web Developer
navigator это клиентская тема. Вам нужно получать IP пользователя из заголовков и с ним стучаться в ваше API
Например так
Ответ написан
В своих проектах решаю эту задачу с помощью такого сниппета.
Помещаете в любой класс статический метод, передаете ему IP пользователя.

public static function ip_info($ip = NULL, $purpose = "location", $deep_detect = TRUE) {
    $output = NULL;
    if (filter_var($ip, FILTER_VALIDATE_IP) === FALSE) {
      $ip = $_SERVER["REMOTE_ADDR"];
      if ($deep_detect) {
        if (filter_var(@$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP))
          $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        if (filter_var(@$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP))
          $ip = $_SERVER['HTTP_CLIENT_IP'];
      }
    }
    $purpose    = str_replace(array("name", "\n", "\t", " ", "-", "_"), NULL, strtolower(trim($purpose)));
    $support    = array("country", "countrycode", "state", "region", "city", "location", "address");
    $continents = array(
      "AF" => "Africa",
      "AN" => "Antarctica",
      "AS" => "Asia",
      "EU" => "Europe",
      "OC" => "Australia (Oceania)",
      "NA" => "North America",
      "SA" => "South America"
    );
    if (filter_var($ip, FILTER_VALIDATE_IP) && in_array($purpose, $support)) {
      $ipdat = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
      if (@strlen(trim($ipdat->geoplugin_countryCode)) == 2) {
        switch ($purpose) {
          case "location":
            $output = array(
              "city"           => @$ipdat->geoplugin_city,
              "state"          => @$ipdat->geoplugin_regionName,
              "country"        => @$ipdat->geoplugin_countryName,
              "country_code"   => @$ipdat->geoplugin_countryCode,
              "continent"      => @$continents[strtoupper($ipdat->geoplugin_continentCode)],
              "continent_code" => @$ipdat->geoplugin_continentCode
            );
            break;
          case "address":
            $address = array($ipdat->geoplugin_countryName);
            if (@strlen($ipdat->geoplugin_regionName) >= 1)
              $address[] = $ipdat->geoplugin_regionName;
            if (@strlen($ipdat->geoplugin_city) >= 1)
              $address[] = $ipdat->geoplugin_city;
            $output = implode(", ", array_reverse($address));
            break;
          case "city":
            $output = @$ipdat->geoplugin_city;
            break;
          case "state":
            $output = @$ipdat->geoplugin_regionName;
            break;
          case "region":
            $output = @$ipdat->geoplugin_regionName;
            break;
          case "country":
            $output = @$ipdat->geoplugin_countryName;
            break;
          case "countrycode":
            $output = @$ipdat->geoplugin_countryCode;
            break;
        }
      }
    }
    return $output;
  }
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы