尝试连接另一个字符串时,字符串值变为未定义

时间:2016-02-08 19:19:24

标签: javascript api scope global-variables

我正在尝试使用openweathermap api。我有一个带有按键lat和amp的坐标对象。 lon等于一个字符串。当我将该coord obj传递给另一个函数并尝试使用api调用字符串连接这些字符串时,它们将变为未定义。我以为我把这些变量的范围全局化了,但似乎并非如此。有人可以告诉我这段代码的错误

var apikey = '9575f3355ae129dc91424b5712a7695e';
var coords = {};
var accessOWM='';

function myLocation(){        navigator.geolocation.getCurrentPosition(function(position)       {
    coords.lat = (Math.round(position.coords.latitude*100)/100).toString();
    coords.lon = (Math.round(position.coords.longitude*100)/100).toString();
  });
}

function changeAccess(coordObj, key){
console.log(coordObj);
accessOWM ='http://api.openweathermap.org/data/2.5/forecast?lat='+coordObj['lat']+'&lon='+coordObj['lon']+'&APPID='+key;
}


myLocation();
console.log(coords);
changeAccess(coords, apikey);
console.log(accessOWM);

4 个答案:

答案 0 :(得分:0)

您遇到异步代码问题。 navigator.geolocation.getCurrentPosition(successCallback)函数是一个异步函数,successCallback不会被执行,但会有一些延迟。这就是为什么当你拨打console.log(coords)changeAccess(coords, apiKey)时,尚未定义坐标。您需要从.getCurrentPosition()回调中调用这些函数(以及最后一个函数)。

答案 1 :(得分:0)

由于coords是在changeAccess的父作用域中声明的,因此您无需将coordObj传递给changeAccess。你试过了吗?

 accessOWM ='http://api.openweathermap.org/data/2.5/forecast?lat='+ coords.lat + '&lon=' + coords.lon + '&APPID='+key;

答案 2 :(得分:0)

这是因为getCurrentPosition方法异步。这意味着在调用getCurrentPosition函数时不会调用changeAccess的回调。因此,您必须将changeAccess调用getCurrentPosition的回调:

function myLocation() {
    navigator.geolocation.getCurrentPosition(function(position) {
        coords.lat = (Math.round(position.coords.latitude*100)/100).toString();
        coords.lon = (Math.round(position.coords.longitude*100)/100).toString();
    });
    changeAccess(coords, apikey);
}

答案 3 :(得分:0)

无论

var apikey = '9575f3355ae129dc91424b5712a7695e';
var accessOWM;

function round(v){ return Math.round(v*100)/100 }

function myLocation(){
    navigator.geolocation.getCurrentPosition(function(position){
        changeAccess(position.coords);
    });
}

function changeAccess(coords){
    console.log(coordObj);
    accessOWM ='http://api.openweathermap.org/data/2.5/forecast?lat=' + round(coords.latitude) + '&lon=' + round(coords.longitude) + '&APPID=' + apikey;
    console.log(accessOWM);
}

myLocation();

或者

var apikey = '9575f3355ae129dc91424b5712a7695e';
var accessOWM = myLocation().then(changeAccess);

accessOWM.then(function(v){
    console.log(v);
})

function round(v){ return Math.round(v*100)/100 }

function myLocation(){
    return new Promise(function(resolve){
        navigator.geolocation.getCurrentPosition(function(position){
            resolve(position.coords);
        });
    });
}

function changeAccess(coords){
    return 'http://api.openweathermap.org/data/2.5/forecast?lat=' + round(coords.latitude) + '&lon=' + round(coords.longitude) + '&APPID=' + apikey;
}