1

I'm having some trouble with function callbacks, specifically with the HTML5 geolocation API. I'm a little new to Js as well. The function:

function getInfo()
{
    navigator.geolocation.getCurrentPosition(getPos);
}

takes a callback parameter of a function that gets the position passed into it.

function getPos(position)
{
PositionObj.lat = position.coords.latitude;
PositionObj.lon = position.coords.longitude;
}

I created a "location" object to store the coordinates, and I'm having trouble returning them.

var PositionObj = 
{
lat:null,
lon:null,
returnLat: function()
             {
             return this.lat;
             },
returnLon: function()
             {
             return this.lon;
             }
};


function printStuff()
{
getInfo();
console.log(PositionObj.returnLat());
}

EDIT: Syntax mistakes fixed. When I call printStuff(), I still get "null."

4

3 回答 3

2
  • 要传递回调,请使用 justgetPos而不是立即调用该函数。
  • 使用正确的语法在PositionObj.

PositionObj = {
    lat: null,
    lon: null,
}
于 2013-06-22T13:20:07.693 回答
1

你的PositionObj文字不正确。初始属性应该用冒号设置:

{ lat: '', lon: '' }
于 2013-06-22T13:19:16.467 回答
1

回调应该告诉您获取位置信息的请求是异步的。这意味着getInfo()不会立即设置值,因此以下行无法访问“新”值。

任何依赖于异步函数结果的东西都必须在回调本身中。

于 2013-06-22T13:55:05.700 回答