2015-09-04 69 views
0

我正在构建一个天气应用程序,其中第一步是检索城市名称的经度和纬度。我正在使用Google地图获取信息。无法将AJAX调用的坐标返回到Google Maps API?

但是我的代码只有当我在调用中返回值时才起作用。我可能对示波器有点模糊,但我确信我的Angular工厂中的代码可以工作。

当我在回调内部登录cords时,它完美地工作,但在它外面返回一个空字符串。

如何从Maps API获取线路,以便在调用天气api时使用它?

在此先感谢您的帮助!

weatherService.getWeather = function(city) { 

     var apiKey = 'cbbdddc644184a1d20ffc4a0e439650d', 
      cords = ''; 

     var geocoder = new google.maps.Geocoder(); 

     geocoder.geocode({'address': city}, function(results, status) { 
      if (status === google.maps.GeocoderStatus.OK) { 
       cords += results[0].geometry.location.lng() + ',' + results[0].geometry.location.lat(); 
       console.log(cords); // works :) 
      } 
     }); 


     var deferred = $q.defer(); 
     var weatherUrl = 'https://api.forecast.io/forecast/' + apiKey + '/' + cords; 

     $http.get(weatherUrl) 
      .success(function(data) { 

       deferred.resolve(data); 

      }).error(function(err) { 

       deferred.reject(err); 

      }); 

     console.log(cords) // nothing 


     return deferred.promise; 

    }; 

    return weatherService; 

编辑:在我的服务中包含一个jQuery同步Ajax调用。直到我对Asynchronous编程更加熟悉之前,现在会这样做。感谢所有帮助的人,非常感谢!

回答

1

对谷歌地图geocode()函数的调用是异步的。尝试像这样:

weatherService.getWeather = function(city) { 

    var apiKey = 'cbbdddc644184a1d20ffc4a0e439650d', 
     cords = ''; 

    var geocoder = new google.maps.Geocoder(); 

    return geocoder.geocode({'address': city}, function(results, status) { 
     if (status === google.maps.GeocoderStatus.OK) { 
      cords += results[0].geometry.location.lng() + ',' + results[0].geometry.location.lat(); 
      console.log(cords); // works :) 
      return getWeatherData(cords); 
     } 
    }); 


    function getWeatherData(coords) { 
     var deferred = $q.defer(); 
     var weatherUrl = 'https://api.forecast.io/forecast/' + apiKey + '/' + coords; 

     $http.get(weatherUrl) 
      .success(function(data) { 

       deferred.resolve(data); 

      }).error(function(err) { 

       deferred.reject(err); 

      }); 

     console.log(coords) // should see the coords 


     return deferred.promise; 
    } 

}; 

return weatherService; 
+0

嘿,那人工作!但我不完全明白为什么,你能解释一下吗?谢谢! – DevonAero

+1

由于'geocode()'是异步的,我们不知道什么时候coords会被返回。通过在geocode()回调中调用'getWeatherData()',我们确保在尝试使用它们之前收到了coords。 – grgdne

+0

我的头脑还是有点困难,有没有什么好的教程可以更深入地解释它?再次感谢男人 – DevonAero

1

我想你应该这样

var cords; 
weatherService.getWeather = function(city) { 

    var apiKey = 'cbbdddc644184a1d20ffc4a0e439650d', 
     cords = ''; 

声明函数

外的VAR线,否则电线的内容是不是在程序的其他部分提供

其次似乎你有在

var weatherUrl = 'https://api.forecast.io/forecast/' + apiKey + '/' + coords; 

有误,使用coords在这个地方,而不是cords

+0

嘿@scaisEdge,谢谢你的回答。我试过了,但仍然没有运气。我编辑了更多信息的OP。再次感谢! – DevonAero

+0

我也发现了一个错误。我已经更新了答案.. – scaisEdge

相关问题