2015-01-06 3 views
-1

Я пытаюсь получить компонентный адрес из системы обратного кодирования и вернуть фактического звонящего. Но даже адрес правильно получается, возвращаемое значение всегда не определено. Вот как я пытаюсь получить адрес.Возвращаемые данные из функции JQuery

var geocoder; 
var addresss = codeLatLng(23.750875259244058, 56822900823215); 
alert(address); 

//Getting the address through reverse geo coding 
var address; 

function codeLatLng(lat, lng) { 
    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; 
         } 
        } 
       } 
       //city data 
       alert(city.short_name + " " + city.long_name) 
       address = city.short_name; 

      } else { 
       alert("No results found"); 
      } 
     } else { 
      alert("Geocoder failed due to: " + status); 
     } 
    }); 
    return address; 
} 
+0

где вы получаете проблемы в коде (в какой строке)? – cracker

+0

Привет, Cracker, Когда я вызываю свою функцию var addresss = codeLatLng (this.getPosition(). Lat(), this.getPosition(). Lng()); Он не возвращает адрес. Внутри моей функции я назначаю адрес, подобный этому адресу = city.short_name; и возвращение в конце адреса возврата; –

+0

plz после трески getPosition() также – cracker

ответ

0

Вы должны использовать jQuery.Deferred(), beacuse - это асинхронная функция.

var geocoder; 
var addresss = codeLatLng(this.getPosition().lat(),  
this.getPosition().lng()); 

// now your addresss wariable is a promise you can access it like this 

addresss.done(function(data){ 
    //data is your resolved addres 
    //do your staff here 
    //Getting the address through reverse geo coding 
    var address = data; 
}) 


function codeLatLng(lat, lng) { 
    var latlng = new google.maps.LatLng(lat, lng); 

    //define jquery deffered 
    var promise= new jQuery.Deferred(); 

    geocoder.geocode({ 'latLng': latlng }, function (results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      console.log(results) 
      if (results[1]) { 
       //formatted address 
       console.log(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; 
         } 
        } 
       } 
       //city data 
       console.log(city.short_name + " " + city.long_name) 
       promise.resolve(city.short_name); 

      } else { 
       console.log("No results found"); 
      } 
     } else { 
      console.log("Geocoder failed due to: " + status); 
     } 
    }); 
    return promise; 

} 

ВАРИАНТ 2 вы можете к нему с помощью функции обратного вызова, как показано ниже

var geocoder; 
var addresss = 
codeLatLng(this.getPosition().lat(), this.getPosition().lng(), function(address){ 
    //do your staff here 
    //Getting the address through reverse geo coding 
}); 


function codeLatLng(lat, lng, callback) { 
    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 
       console.log(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; 
         } 
        } 
       } 
       //city data 
       console.log(city.short_name + " " + city.long_name) 
       //callback your address here 
       callback(city.short_name); 

      } else { 
       console.log("No results found"); 
      } 
     } else { 
      console.log("Geocoder failed due to: " + status); 
     } 
    }); 
    callback(false); 

} 
+0

Спасибо Мехмет. Это то, что я смотрел. –

0

geocoder.geocode() функция асинхронная, с функцией обратного вызова, которая запускается после получения ответа от Google было получено. Но в вашем случае оператор return address; находится вне функции обратного вызова, поэтому codeLatLang(lat,lng) возвращает адрес до того, как ответ будет полностью принят, и до того, как переменной адреса присвоено значение.

Перемещение вашего оператора return address внутри функции обратного вызова исправит это.

(Убедитесь, что возвращать соответствующие значения ошибок в случае неудачного ответа.)

Смежные вопросы