不能从AJAX调用Google Maps API返回坐标
Can't return coordinates from AJAX call to Google Maps API?
我正在构建一个天气应用程序,其中第一步是检索城市名称的经度和纬度。我正在使用谷歌地图获取信息。
然而,我的代码只有在调用内部返回值时才能工作。我可能对作用域有点模糊,但我认为我的Angular工厂中的代码肯定可以工作。
当我在回调中记录cords
时,它工作得很好,但在外面它返回一个空字符串。
我怎样才能从地图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调用。在我熟悉异步编程之前,暂时就这样了。谢谢所有的帮助,伙计们,真的很感激!
对Google Maps 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;
我认为你应该在函数之外声明变量
this way
var cords;
weatherService.getWeather = function(city) {
var apiKey = 'cbbdddc644184a1d20ffc4a0e439650d',
cords = '';
否则,在程序的其他部分中无法获得声带内容
第二,你似乎在
有一个错误var weatherUrl = 'https://api.forecast.io/forecast/' + apiKey + '/' + coords;
此处使用coords
而不是cords
相关文章:
- 敲除:可观察数组没有被正确绑定——只有1个结果显示,而api返回6
- Google Directions API返回不同的waypoint_order和legs
- PhoneGap API返回时间戳格式
- Angular promise从JSON API返回不正确的数据
- 从Google Maps API返回的jQuery格式时间
- Google Feed API-返回媒体:缩略图
- Gmail API 返回 400 个带有批处理请求的错误请求
- 谷歌地图API - 返回60多个地名用于雷达搜索
- 如何从谷歌地图API返回的结果数组中提取城市名称
- 无法使用 AJAX 获取 url 的 StumbleOn 视图,因为它的 API 返回文本/纯文本
- 从 Meteor 中的 Stripe API 返回的 JSON 字典中的访问值
- API 返回 404,但记录插入到数据库中
- 设置要使用 Facebook API 返回的评论数
- 如何从使用 API 返回的 JSON 对象初始化 google.maps.DirectionsResult
- 如何访问维基百科 API 返回的 JSON 中的嵌套对象
- 如何使用脚本获得格子 api 返回的响应
- 节点 js 与 gmail api,API 返回错误:错误:unauthorized_client
- 从开放天气图 API 返回的数据没有意义
- Web API 2 - 返回 pdf,在客户端 (AngularJs) 上显示/下载收到的 pdf 文件
- 使用反向地理编码API返回JSON