基于坐标的请求不起作用

时间:2013-12-11 16:16:15

标签: javascript yelp

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

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中写一个坐标,请求代码就可以了。

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

1 个答案:

答案 0 :(得分:2)

Geolocation 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;
        }
    });
}