简体   繁体   English

一般的javascript

[英]general javascript

i havent written in js in awhile and am a bit rusty apparently. 我有一段时间没有用js编写,显然有点生锈。 trying to understand the following problem. 试图了解以下问题。 the alert in getCurrentPosition successCallback shows the latitude correctly, but the last line alerts undefined . getCurrentPosition successCallback中的警报可正确显示纬度,但最后一行警报undefined why isnt my client_location function returning the latitude when call outside the function? 为什么我的client_location函数在函数外调用时不返回纬度?

client_location = function() {
  if (navigator.geolocation) {
    return navigator.geolocation.getCurrentPosition(function(position) {
      alert(position.coords.latitude);  ## RETURNS LATITUDE CORRECTLY ##
      return position.coords.latitude;
    });
  }
};
alert(client_location());               ## RETURNS UNDEFINED ##

You're passing a callback to getCurrentPosition and your alert is inside that callback. 您正在将回调传递给getCurrentPosition并且alert位于该回调内。 Your return position.coords.latitude is also inside that callback. 您的return position.coords.latitude也位于该回调中。 Your client_location function returns whatever getCurrentPosition returns and getCurrentPosition doesn't return anything . 您的client_location函数返回getCurrentPosition返回的内容,而getCurrentPosition不返回任何内容

If you want to do something with the latitude, you'll have to do it inside your callback; 如果您想对纬度做一些事情,则必须在回调中完成; you could hand client_location a callback like this: 您可以将client_location传递给这样的回调:

client_location = function(callback) {
  if (navigator.geolocation) {
    return navigator.geolocation.getCurrentPosition(function(position) {
      callback(position.coords.latitude);
    });
  }
};

client_location(function(lat) {
    alert(lat);
});

If the device does not return a geolocation it is undefined. 如果设备未返回地理位置,则未定义。 Add an else statement to deal with no geolocation. 添加else语句以解决没有地理位置问题。

client_location = function() {
  if (navigator.geolocation) {
    return navigator.geolocation.getCurrentPosition(function(position) {
      alert("clientLocation: "+position.coords.latitude);
      return position.coords.latitude;
    });
  }else{
    return("no navigator.geolocation");  
  }
};
alert(client_location()); 

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

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