Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 基于坐标的请求不起作用_Javascript_Yelp - Fatal编程技术网

Javascript 基于坐标的请求不起作用

Javascript 基于坐标的请求不起作用,javascript,yelp,Javascript,Yelp,我想做的是确定用户的位置,然后根据他的位置向YelpAPI发出请求 function getLocation() { if (navigator.geolocation) { var y = navigator.geolocation.getCurrentPosition(showPosition); return y; } else{x.innerHTML="Geolocation is not supported by this browser."

我想做的是确定用户的位置,然后根据他的位置向YelpAPI发出请求

function getLocation()
  {
  if (navigator.geolocation)
    {
    var y = navigator.geolocation.getCurrentPosition(showPosition);
    return y;
    }
  else{x.innerHTML="Geolocation is not supported by this browser.";}
  }
function showPosition(position)
  {
 var y = position.coords.latitude + 
  "," + position.coords.longitude;
  return y;
  }


function doRequest(){

var terms = 'turkish';
var near = 'San+Francisco';
var ll = getLocation();
... }
我已经测试了变量y,它给出了真实的纬度和经度,如果我在ll中给self写了一个坐标,请求代码就行了


问题是,在这种情况下,我的ll参数在请求中似乎“未定义”,我无法从API接收任何响应。我不明白问题出在哪里。有什么想法吗

地理位置API是异步的,因此您必须等待数据返回

function getLocation(callback) {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            callback({
                success : true, 
                result  : position.coords.latitude + "," + position.coords.longitude
            });
        });
    } else {
        callback({
            success : false, 
            result  : "Geolocation is not supported by this browser."
        });
    }
}

function doRequest() {
    var terms = 'turkish';
    var near = 'San+Francisco';
    getLocation(function(result) {
        if (result.success) {
            var y = result.result;

            // do something with y here
        }else{
            x.innerHTML = result.result;
        }
    });
}

似乎
getLocation()
函数没有返回。它是否会通过
else
分支?不会,因为我已经测试了代码。如果是这样,我就不会收到坐标。我写测试代码并不是为了让它简单易懂,我不确定我是否理解这种情况。
ll
变量是否未定义?如果没有,问题出在哪里?getCurrentPosition没有返回任何内容,也没有立即调用showPosition。它可能会等待位置,然后调用showPosition。阅读关于异步编程的文章,在JS中,大多数事情都是这样做的。好吧,lupatus是绝对正确的。这是我错过的一点。谢谢我已经试过了,但是仍然没有找到我需要的ll参数<代码>变量ll=-1;getLocation(function(result){if(result.success){ll=result.result;..当我在请求中使用ll时,它仍然是未定义的。您只能在回调中使用它,地理位置是异步的,因此它稍后返回坐标,请阅读此->