Lime Survey - параметры ответа геолокации (город, страна) возвращаются в конечном URL

LimeSurvey - щелкните URL-адрес опроса, попросите пользователя разрешить или заблокировать местоположение

т.е. скрипт геолокации запускается и возвращает текущий город и страну в конечном URL-адресе.

Это возможно или нет. Ниже мой скрипт, как реализовать это в обзоре извести.

Любые предложения, пожалуйста

<script type="text/javascript"> 

  var geocoder;

  if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
  } 

   function initMap(){
    }

   //Get the latitude and the longitude;
   function successFunction(position) {
  var lat = position.coords.latitude;
  var lng = position.coords.longitude;
   codeLatLng(lat, lng)
 }

 function errorFunction(){
alert("Geocoder failed");
}

function codeLatLng(lat, lng) {

alert("Latitude: "+lat);
alert("Longtude: "+lng);

geocoder = new google.maps.Geocoder();

var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
  //console.log(results)      
    if (results[1]) {
     //formatted address                
     alert(results[0].formatted_address)         
    //find country name
    for (var i=0; i<results[0].address_components.length; i++) {
      for (var b=0;b<results[0].address_components[i].types.length;b++) {

        //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
            if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
                //this is the object you are looking for
                city= results[0].address_components[i];
                break;
            }
            if(results[0].address_components[i].types[b] == 'country'){
              country = results[0].address_components[i];
              break;
            }
      }
    }        
    //city data
    alert(city.short_name + " " + city.long_name)
    //country data
    alert(country.short_name + " " + country.long_name)

    } else {
      alert("No results found");
    }
  } else {
    alert("Geocoder failed due to: " + status);
  }
});
 }   </script> 
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&callback=initMap"
type="text/javascript"></script>

Любая помощь? Заранее спасибо.


person bashirudeen ahmad    schedule 25.01.2017    source источник


Ответы (2)


Если ваш код работает (иначе: сначала просмотрите свой код). Я говорил только за часть LimeSurvey.

  1. Create a multiple text question type :
    • code GEO
    • Добавьте 2 кода подвопроса CITY и CONTRY
  2. Добавьте класс (используя дополнительные настройки) hidden, тогда вопрос не будет отображаться.
  3. Деактивируйте редактор HTML и поместите свой скрипт в jquery ready (в качестве альтернативы используйте addScriptToQuestion плагин)
  4. Добавьте пробел или перевод строки после каждого { в вашем коде js (и пробел перед каждым } )
  5. replace you last alert (where you have city.data and coutry.data) by
    • $("#answer{SGQ}CITY").val(city.short_name + " " + city.long_name); for city
    • $("#answer{SGQ}COUNTRY").val(country.short_name + " " + country.long_name); для страны
  6. Вы можете использовать {GEO_CITY} и {GEO_COUNTRY} в опросе (после этой страницы)
  7. Затем вы можете использовать его в своем URL-адресе http://example.org/?city={GEO_CITY}&country={GEO_COUNTRY}

Использование LimeSurvey версии 2.50 и выше (иначе нужен javascript, чтобы скрыть вопрос)

person Denis Chenu    schedule 25.01.2017
comment
Денис, у вас опечатка во втором селекторе - должно быть $(#answer{SGQ}COUNTRY) - person tpartner; 26.01.2017
comment
Да, исправлено. Но глядя на исходный код js: не уверен, что он здесь работает;) - person Denis Chenu; 26.01.2017
comment
Денис, большое спасибо, можно сохранить город, страну в таблице ответов Lime db при отправке опроса. - person bashirudeen ahmad; 28.01.2017
comment
@bashirudeenahmad: да ... код хранит город и страну в БД. В 2 подвопросах .... Это точная цель этого кода .... Здесь: я действительно не уверен, что ваш код работает (в LS или нет). - person Denis Chenu; 29.01.2017

Эта сокращенная версия работает для меня, когда она помещается в источник скрытого вопроса с несколькими короткими текстами, как предлагает Денис:

var geocoder;

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} 

//Get the latitude and the longitude;
function successFunction(position) {
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    codeLatLng(lat, lng)
}

function errorFunction(){
    console.log("Geocoder failed");
}

function codeLatLng(lat, lng) {

    geocoder = new google.maps.Geocoder();

    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({ 
    'latLng': latlng },
    function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[1]) {
                for (var i=0; i<results[0].address_components.length; i++) {
                    for (var b=0;b<results[0].address_components[i].types.length;b++) {
                        // Find city name
                        // There are different types that might hold a city
                        // "locality" works for most of North America
                        // See here for types - https://developers.google.com/maps/documentation/geocoding/intro
                        if (results[0].address_components[i].types[b] == "locality") {
                            //this is the object you are looking for
                            city= results[0].address_components[i];
                            break;
                        }
                        // Find country name
                        if(results[0].address_components[i].types[b] == 'country'){
                            country = results[0].address_components[i];
                            break;
                        }
                    }
                }        
                // City data
                //console.log(city.short_name + " " + city.long_name);
                $("#answer{SGQ}CITY").val(city.long_name);
                // Country data
                //console.log(country.short_name + " " + country.long_name);
                $("#answer{SGQ}COUNTRY").val(country.long_name);
            } 
            else {
                console.log("No results found");
            }
        } else {
            console.log("Geocoder failed due to: " + status);
        }
    });
}   

`

person tpartner    schedule 27.01.2017