不能从AJAX调用Google Maps API返回坐标

Can't return coordinates from AJAX call to Google Maps API?

本文关键字:API 返回 坐标 Maps Google AJAX 调用 不能      更新时间:2023-09-26

我正在构建一个天气应用程序,其中第一步是检索城市名称的经度和纬度。我正在使用谷歌地图获取信息。

然而,我的代码只有在调用内部返回值时才能工作。我可能对作用域有点模糊,但我认为我的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