我正在构建一个天气应用程序,其中第一步是检索城市名称的经度和纬度。我正在使用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编程更加熟悉之前,现在会这样做。感谢所有帮助的人,非常感谢!
嘿,那人工作!但我不完全明白为什么,你能解释一下吗?谢谢! – DevonAero
由于'geocode()'是异步的,我们不知道什么时候coords会被返回。通过在geocode()回调中调用'getWeatherData()',我们确保在尝试使用它们之前收到了coords。 – grgdne
我的头脑还是有点困难,有没有什么好的教程可以更深入地解释它?再次感谢男人 – DevonAero