简体   繁体   English

从JavaScript函数返回多个值,从而在Google Maps V3中给出错误

[英]Return Multiple Values From javascript function giving Error in Google Maps V3

What I want to do is that I need to create markers from stored location of user. 我想做的是我需要从用户的存储位置创建标记。 So for that I need latitude and longitude. 因此,我需要纬度和经度。 I got the lat & lon in my function get_current_user_lat_lon . 我在函数get_current_user_lat_lon中得到了纬度和经度。 Now I want to return both lat & lon through Object but my return is not working.... 现在我想通过Object返回lat和lon,但是返回不起作用。

function initialize(){
    var var_get_current_user_lat_lon = get_current_user_lat_lon(); 
    var latitutde = var_get_current_user_lat_lon.latitutde;
    alert(latitutde);// not even alert
    var longitutde = var_get_current_user_lat_lon.longitutde;
    alert(longitutde); // not even alert
}        

function get_current_user_lat_lon(){
    var address = $("#hidden_current_location").val();//Working fine
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var variable = results[0].geometry.location;
            var lat  = variable.lat();
            var lon  = variable.lng();
            alert(lat); //Working fine
            alert(lon); //Working fine
            //return not working here
        }
        //return not working here
    });
    return {latitutde: lat , longitutde : lon};// giving error lat.lon is not defined means return not working here
}

Your "lat" and "lon" variables are declared inside the callback from "geocode()". 您的“ lat”和“ lon”变量 “ geocode()”的回调中声明。 Even if you declared them outside it, however, the overall idea would not work. 但是,即使您在外面声明了它们,整个想法也行不通。 The "geocode()" function is asynchronous ; “ geocode()”函数是异步的 that's the reason there's a callback function in the first place. 这就是首先有一个回调函数的原因。

Instead of structuring your code so that your "get_current_user_lat_lon()" function returns a value, follow the lead of the Google architecture and make your own function take a callback: 与其结构化代码以使您的“ get_current_user_lat_lon()”函数返回一个值,不如遵循Google体系结构的先例并让您自己的函数进行回调:

function get_current_user_lat_lon( callback ){
  var address = $("#hidden_current_location").val();//Working fine
  geocoder = new google.maps.Geocoder();
  geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var variable = results[0].geometry.location;
        var lat  = variable.lat();
        var lon  = variable.lng();
        callback({latitude: lat, longitude: lon});
      }

  });

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM