试图获得当地的天气

时间:2016-02-25 03:41:16

标签: javascript geolocation

我想通过获取currentposition并将其传递给网址以获取结果来获取当地天气。我似乎无法传递getCurrentPosition之外的坐标。

我的代码是:http://codepen.io/rush86999/pen/MKMywE

if (navigator.geolocation) {
//position.coords.longitude

var app = {

    getGeoLoc: function(id) {

        var self = this;

        navigator.geolocation.getCurrentPosition(function(position) {

            var myVar1, myVar2, myVar3; // Define has many variables as you want here

            // From here you can pass the position, as well as any other arguments 
            // you might need. 
            self.foundLoc(position, self, myVar1, myVar2, myVar3);

        }, this.noloc, {
            timeout: 3
        });
    },

    foundLoc: function(position, self, myVar1, myVar2, myVar3) {
        this.latituide = position.coords.latituide;
        this.longitude = position.coords.longitude;
        console.log('#4 position coords work in foundLoc: ', this.latitude, this.longitude);
    },
    latitude: '',
    longitude: ''

};

console.log('#5 found loc in app, ', app.foundLoc);

var url = 'api.openweathermap.org/data/2.5/weather?lat=' + app.latitude + '&lon=' + app.longitude + '&APPID=7bda183adf213c8cfa2ef68635588ef3';

//lets look inside url
console.log('#1 url has coordinates: ', url);

1 个答案:

答案 0 :(得分:0)

这里有几个问题。

  • 首先,您似乎没有调用getGeoLoc方法,因此这将是第一个修复。
  • 您添加了this.noloc的错误回调,但它未包含在您的对象中。
  • 您的坐标有几个拼写错误
  • 您在地理定位解决之前提出了API请求,因此app.latitudeapp.longitude将是未定义的。理想情况下,这应该包含在成功地理定位请求调用的方法中。

    var app = {
    
      getGeoLoc : function (id) {
          //Removed timeout option due to error
          var options = {}; //{ timeout: 3 };
          navigator.geolocation.getCurrentPosition(this.foundLoc.bind(this), this.noloc, options);
      },
    
      foundLoc : function(position) {
        this.latitude = position.coords.latitude;
        this.longitude = position.coords.longitude; 
        console.log('coords ', this.latitude, this.longitude);
        // Call your get weather function
        // Using call to bind the context of `this`
        this.getWather.call(this);
      },
      // Error method
      noloc: function(err) {
         console.log(err.message);
      },
      // Method to get your weather after location is found
      getWather: function() {
    
          var url = 'http://api.openweathermap.org/data/2.5/weather?lat=' + this.latitude + '&lon='  + this.longitude +'&APPID=7bda183adf213c8cfa2ef68635588ef3';
          console.log('URL is: '+url);
          $.getJSON(url, function(data) {
            console.log('Your weather data', data);
            // Do your dom stuff here
          });
      },
      latitude: '',
      longitude: ''
    };
    
    // Make sure to call your initialising function
    app.getGeoLoc();
    

注意:我已删除演示的HTML内容,并删除了超时选项,因为它导致错误。

Link to forked codepen