为什么函数返回未定义

时间:2015-08-20 15:26:15

标签: javascript geolocation

有人可以帮助我理解为什么以下警报未定义,我感觉需要回调,但我不确定。基本上我想做的就是返回这个函数,然后将它添加到一个html元素。

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        alert("Geolocation is not supported by this browser.");
    }
}

function showPosition(position) {

    var lat = position.coords.latitude;
    var lon = position.coords.longitude;

    var lat1 = <?php echo the_sub_field('google_maps_lat'); ?>;
    var lon1 = <?php echo the_sub_field('google_maps_long'); ?>;

    var R = 6371; // Radius of the earth in km
    var dLat = deg2rad(lat1-lat);  // deg2rad below
    var dLon = deg2rad(lon1-lon); 
    var a = 
        Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat)) * 
        Math.sin(dLon/2) * Math.sin(dLon/2); 

    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    var d = R * c; // Distance in km

    //if i alert here it would show the correct results
    return d                            
}

function deg2rad(deg) {
    return deg * (Math.PI/180)
}

//This returns undefined
alert(getLocation());

3 个答案:

答案 0 :(得分:1)

getLocation()无法返回值,因为navigator.geolocation.getCurrentPosition是一个异步函数,期望回调在成功和错误时运行。

因此,即使您有return语句,它也会始终返回undefined,因为它的工作我们只能在return之后完成调用

要解决这个问题,你应该使用promises。以下示例适用于本机javascript promises,IE不支持。如果您需要IE支持,请使用promises库,例如bluebird

function getLocation() {
    return new Promise(function(resolve, reject) { // create a new promise
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) { // send the callback to getCurrentPosition()
                resolve(showPosition(position)); // when the callback is invoked resolve using the result of showPosition()
            }, function(PositionError) { // error callback
                reject(PositionError); // reject using the PositionError from the callback
            });
        } else {
            alert("Geolocation is not supported by this browser.");
            reject('not supported'); // if not supported reject
        }
    });
}

getLocation().then(function(result) { // use the promise then to get the result and display it in the alert
    alert(result);
});

答案 1 :(得分:0)

 var options = {
 enableHighAccuracy: true,
 timeout: 5000,
 maximumAge: 0
 };

function getLocation() {
   if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition, error, options);
   } else {
      alert("Geolocation is not supported by this browser.");
   }

return 'whatever you want to return when it fails';
}

function error(err) {
   console.warn('ERROR(' + err.code + '): ' + err.message);
};


function showPosition(position) {
  var lat = position.coords.latitude;
  var lon = position.coords.longitude;

  var lat1 = <?php echo the_sub_field('google_maps_lat'); ?>;
  var lon1 = <?php echo the_sub_field('google_maps_long'); ?>;

  var R = 6371; // Radius of the earth in km
  var dLat = deg2rad(lat1-lat);  // deg2rad below
  var dLon = deg2rad(lon1-lon); 
  var a = 
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat)) * 
    Math.sin(dLon/2) * Math.sin(dLon/2); 

  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
  var d = R * c; // Distance in km

  //do whatever with d
  callSomeOtherFunction(d)                            
}

答案 2 :(得分:0)

正如@Pointy所提到的,你不能通过异步API返回值。

尝试使用全局变量。

    var desiredValue;

    function showPosition(position) {
        /*
             Rest of the function
        */
        desiredValue = d;  
    }

    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        } else {
            alert("Geolocation is not supported by this browser.");
        }
    }

    getLocation();
    alert(desiredValue);
相关问题